constant {gestalt} | R Documentation |
Values as Functions
Description
A constant is a fixed value that incorporates its very computation. This
is none other than a function that computes a fixed value when called
without arguments. constant()
declares such a function as a bona fide
constant by transforming it to a function that caches the value of its void
call (i.e., constant()
memoizes void functions).
Combine %>>>%
with constant()
for a lazy, structured
alternative to the
magrittr `%>%`
operator (see ‘Examples’).
Usage
constant(f)
variable(f)
Arguments
f |
Function, or symbol or name (string) thereof, that can be called
without arguments. (NB: |
Value
constant()
yields a function without formal arguments that returns
the (cached, visibility-preserving) value of the void call f()
.
variable()
is the inverse transformation of constant()
: it
recovers the underlying (uncached) function of a constant function.
See Also
Examples
# Function with a constant return value
val <- {message("Computing from scratch"); mtcars} %>>>%
split(.$cyl) %>>>%
lapply(function(data) lm(mpg ~ wt, data)) %>>>%
lapply(summary) %>>>%
sapply(`[[`, "r.squared")
# With every invocation, `val()` is computed anew:
val()
val()
# Declaring `val` as a constant ensures that its value is computed only once.
# On subsequent calls, the computed value is simply fetched:
const <- constant(val)
const()
const()
# As values, `val()` and `const()` are identical. But `const()`, moreover,
# has structure, namely the function `const`:
const
# For instance, you can inspect the intermediate summaries:
head(const, -1)()
# Which can itself be a constant:
summ <- constant(head(const, -1))
summ()
summ()
## Not run:
# Think of `%>>>%` combined with `constant()` as a lazy, structured
# alternative to the magrittr `%>%` operator.
library(magrittr)
val2 <- mtcars %>%
split(.$cyl) %>%
lapply(function(data) lm(mpg ~ wt, data)) %>%
lapply(summary) %>%
sapply(`[[`, "r.squared")
# `val2` and `const()` are identical values. But whereas `val2` is computed
# immediately and carries no structure, `const` embodies the process that
# produces its value, and allows you to defer its realization to the
# invocation `const()`.
stopifnot(identical(val2, const()))
## End(Not run)
# Use `variable()` to recover the original (\dQuote{variable}) function
val_var <- variable(const)
stopifnot(identical(val_var, val))
val_var()
val_var()