r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
410 stars 56 forks source link

Empty matrix in R6 class with arguments defined - Julia structure/Python class translation #199

Closed iembry closed 4 years ago

iembry commented 4 years ago

Hi, I am attempting to translate a Julia mutable structure/Python class (see both below) into an R6 class. I have asked for assistance at StackOverflow (https://stackoverflow.com/questions/59041632/r-translating-python-class-to-rs-r6-class-unique-names-error) because I received an error message about names not being unique.

# Julia structure

mutable struct LetterGrid
    nattempts::Int
    nrows::Int
    ncols::Int
    cells::Matrix{Char}
    solutions::Vector{String}
    LetterGrid() = new(0, nrows, ncols, fill(' ', nrows, ncols), Vector{String}())
end

# Python 3.x class

class Grid:
    def __init__(self):
        self.num_attempts = 0
        self.cells = [['' for _ in range(n_cols)] for _ in range(n_rows)]
        self.solutions = []

The following is my attempt at creating a R6 class to replicate the Julia structure/Python class.

library("R6")

Grid <- R6Class("Grid",
public = list(
num_attempts = NULL,
cells = NULL,
solutions = NULL,
initialize = function(num_attempts = NA, cells = NA, solutions = NA) {
self$num_attempts <- 0
self$cells <- cells
self$solutions()
},
cells = function(val) {
for (val in seq_along(ncols)) {
for (val in seq_along(nrows))
{
result <- vector("character")
result
}
}
}
)
)

I don't think that what I wrote for the R6 class actually fully represents the Julia structure/Python class.

How do you create an empty matrix that is filled in with outside variables in an R6 class?

Thank you.

wch commented 4 years ago

It's because you have cells = NULL and cells = function(val) ..... You'll need to remove one of them.

iembry commented 4 years ago

@wch Thank you for the suggestion. I removed cells = NULL and it worked.