future (version 1.0.1)

lazy: Create a lazy future whose value will be resolved at the time when requested

Description

A lazy future is a future that uses lazy evaluation, which means that its value is only computed and resolved at the time when the value is requested. This means that the future will not be resolved if the value is never requested.

Usage

lazy(expr, envir = parent.frame(), substitute = TRUE, globals = TRUE, local = TRUE, gc = FALSE, earlySignal = FALSE, ...)

Arguments

expr
envir
The environment in which the evaluation is done (or inherits from if local is TRUE) and from which globals are obtained.
substitute
If TRUE, argument expr is substitute():ed, otherwise not.
globals
If TRUE, global objects are resolved ("frozen") at the point of time when the future is created, otherwise they are resolved when the future is resolved.
local
If TRUE, the expression is evaluated such that all assignments are done to local temporary environment, otherwise the assignments are done in the calling environment.
gc
If TRUE, the garbage collector run after the future is resolved (in the process that evaluated the future).
earlySignal
Specified whether conditions should be signaled as soon as possible or not.
...
Not used.

Value

A LazyFuture.

Details

The preferred way to create a lazy future is not to call this function directly, but to register it via plan(lazy) such that it becomes the default mechanism for all futures. After this future() and %<=%< a=""> will create lazy futures.

Examples

Run this code
## Use lazy futures
plan(lazy)

## A global variable
a <- 0

## Create lazy future (explicitly)
f <- future({
  b <- 3
  c <- 2
  a * b * c
})

## Although 'f' is a _lazy_ future and therefore
## resolved/evaluates the future expression only
## when the value is requested, any global variables
## identified in the expression (here 'a') are
## "frozen" at the time point when the future is
## created.  Because of this, the 'a' in the
## the future expression preserved the zero value
## although we reassign it in the global environment
a <- 7
print(a)

v <- value(f)
print(v)
stopifnot(v == 0)


## Another example illustrating that lazy futures go
## hand-in-hand with lazy evaluation of arguments

## A function that may or may not touch it's argument
foo <- function(a, use=FALSE) {
  cat("foo() called\n")
  if (use) cat("a=", a, "\n", sep="")
}

## Create a future
x %<-% { cat("Pow!\n"); 1 }

## Lazy evaluation where argument is not used
foo(x, use=FALSE)
# Outputs:
# foo() called

## Lazy evaluation where argument is used
## Hint: 'x' will be resolved
foo(x, use=TRUE)
# Outputs:
# foo() called
# Pow!
# a=1

## Lazy evaluation where argument is used (again)
## Hint: 'x' is already resolved
foo(x, use=TRUE)
# Outputs:
# foo() called
# a=1

Run the code above in your browser using DataLab