setCached {depcache}R Documentation

Cache-tracking assignment

Description

Cache expression values and automatically recalculate them when their dependencies change

Usage

  symbol %<-% expr
  expr %->% symbol
  setCached(symbol, expr, extra = NULL, ...)

Arguments

symbol

A variable name to associate with the expression, unquoted.

expr

The expression to cache, taking dependencies into account.

extra

An unquoted expression to be considered an extra part of the state, in addition to the automatically determined dependencies. Will be evaluated every time the variable is accessed to determine whether it should be recalculated.

...

Additional settings, see depcache.options.

Details

Sets up the variable symbol to automatically recalculate the value of expr any time its dependencies change, using makeActiveBinding and the same mechanisms that power cache.

Initially, expr is loaded from cache or evaluated, and the hash is remembered. When the variable named by symbol is accessed, its dependencies are hashed together with expr (this may be done recursively if the dependencies are themselves active bindings set up the same way). If the hash changes, the value of expr is again loaded from cache (if available) or evaluated anew.

To prevent infinite loops during dependency calculation, symbol is automatically skipped, but a self-dependent expr is probably a bad idea anyway.

Value

Returns the value of expr, invisibly. Called for the side effect of creating an active binding with a name specified by symbol.

See Also

cache, makeActiveBinding

Examples

  
  a <- 1
  # will evaluate the expression first
  x %<-% { message('evaluating expression "x"'); a + 1 }
  x # 2
  # will reuse cached value
  {
    message('evaluating expression "y"')
    a + 1
    # even if written a bit differently
  } %->% y
  y # 2
  a <- -1
  # will evaluate the expression again
  x # 0
  # will load the new cached value
  y # 0
  setCached(z, x + y)
  a <- 0
  z # recalculates all three
  

[Package depcache version 0.1-2 Index]