[R] "use of NULL environment is defunct" when trying to lock a reference class

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Tue Aug 28 22:49:17 CEST 2018


Hi Eric,

Thank you for your answer!

On Mon, 27 Aug 2018 21:48:50 +0300
Eric Berger <ericjberger using gmail.com> wrote:

> you might want to consider the more recent R6 package

Indeed, R6 has private fields which fits my idea of an object with
mutable state even better.

My original problem seems to be solved and I'm posting my code (CC0) in
case someone else needs it as a reference:

require(digest); require(R6)
memoised <- R6Class(
	"memoised", lock_objects=T, lock_class=T, cloneable=F,
	private=list(fun=NULL, storage=NULL, cache=NULL),
	public=list(
		initialize=function(fun, storage) { # constructor
			private$fun <- fun
			private$storage <- storage
			private$cache <- tryCatch(
				{
					load(storage)
					cache
				}, error = function(e) {
					new.env(T, emptyenv())
				}
			)
		},
		eval=function(...) { # behave as cached fun
			hash <- digest(list(...), algo="sha1")
			if (exists(hash, private$cache)) return(get(hash, private$cache))
			val <- private$fun(...)
			assign(hash, val, private$cache)
			val
		},
		par.eval=function(args, cl) { # args is list of argument lists
			# hash all because we'll need them later
			hashes <- lapply(args, digest, algo="sha1")
			# indices of not yet evaluated in the original args array
			missing <- Filter(function(i) !exists(hashes[[i]], private$cache), seq_along(args))
			# evaluate and save them
			values <- parLapply(cl, args[missing], function(l) do.call(private$fun,l))
			private$cache[hashes[missing]] <- values
			# get all requested hashes
			private$cache[hashes]
		},
		finalize=function() { # destructor
			cache <- private$cache # must have known name for restore
			save(cache, file=private$storage)
		}
	)
)

It's still a mystery why did setRefClass refuse to lock my class, but
at least it's not blocking my progress.

-- 
Best regards,
Ivan




More information about the R-help mailing list