Skip to content
Prev 302610 / 398503 Next

Force evaluation of a symbol when a function is created

On 12-08-07 10:46 AM, Bert Gunter wrote:
You still need force:

fy <- function(Y)function(x) x*Y
Y <- 2
F <- fy(Y)
Y <- 3
F(5)

This will print 15, because F only contains a promise to evaluate Y, it 
hasn't been evaluated until the very last line, and by that time Y has 
been changed to 3.

If you are going to construct functions in functions, and their results 
depend on the arguments to the constructor, then it's almost always a 
good idea to force the arguments.  Sometimes it isn't necessary (the 
value will be forced implicitly), and in some rare circumstances you 
might want to capture the promise instead of its value, but it's 
generally a good idea.  It is a fairly cheap operation.

Duncan Murdoch