Accumulator Generator with R

Paul Graham ( http://www.paulgraham.com/accgen.html ) gives the following problem:

Write a function foo that takes a number n and returns a function that takes a number i, and returns n incremented by i.

In R, we could write it like this:

foo <- function (n)
    function (i) (n <<- n + i)

We can create a new function fun

fun <- foo(2.43)
fun
function (i) (n <<- n + i)
<environment: 0x3831bc8>

… and test it.

fun(1.1)
fun(1.1)
fun(2.1)
[1] 3.53
[1] 4.63
[1] 6.73

Without the parentheses around n <<- n + i, the new function would return n invisibly. So it would still work, but we would need to call print explicitly.

foo <- function (n)
    function (i) n <<- n + i
fun <- foo(1.1)
fun
function (i) n <<- n + i
<environment: 0x3aad238>
fun(2.1)
print(fun(3.1))  ## 1.1 + 2.1 + 3.1
[1] 6.3

(the tangled R-code)

return to main page...

return to R page...