The following simplified version of my program captures the confusion.
I am trying to create a set of functions f1, f2, ..., fK, ..., fn defined as fK(x) = print(K + x). For this, I created the function factory:
factory = function (K) {
function (x) print(K + x)
}
And use it to create 5 functions: funcs = sapply(1:5, factory)
I call them one by one, for the same value: x = 10
callOnef = function (f, x) f(x)
sapply(funcs, callOnef, 10)
I expected the output to be (one per line) 11 12 13 14 15, but I instead got (one per line) 15 15 15 15 15 and on the 6th line, a row of five 15 's.
When I inserted a print(K)
in the definition of factory
, the output changed to (one per line) 11 12 13 14 15 and on the 6th line, a row of 11 12 13 14 15. (Ignoring the output of print(K) itself, that preceded the 6 lines)
This confused me a lot. I found a thread where there's a suggestion to use force
.
So, I replaced print(K)
with force(K)
:
factory = function (K) {
force(K)
function (x) print(K + x)
}
The output is now (one per line) 11 12 13 14 15 and on the 6th line, a row of 11 12 13 14 15.
Questions:
- Why does the evaluation of K (like in my case through
print(K)
orforce(K)
,) change the behavior of the closure? - Why the 6th line? It looks identical to the output of print(K + 10) if K was a vector equal to 1:5.