[R] functional (?) programming in r

From: Wacek Kusnierczyk <Waclaw.Marcin.Kusnierczyk_at_idi.ntnu.no>
Date: Mon, 17 Nov 2008 22:28:05 +0100

the following is a trivialized version of some functional code i tried to use in r:

(funcs = lapply(1:5, function(i) function() i))
# a list of no-parameter functions, each with its own closure environment,
# each supposed to return the corresponding index when applied to no

sapply(funcs, function(func) func())
# supposed to return c(1,2,3,4,5)

there is absolutely nothing unusual in this code, in the context of functional programming.
the following is my best translation to python (modulo indexing, which is inessential), where it does what i wanted:

funcs = map(lambda i: lambda: i, range(5)) map(lambda func: func(), funcs)
# [0,1,2,3,4]

all these functions have distinct environments:

(envs = sapply(funcs, function(func) environment(func))) assign("i", 0, environment(envs[[1]]))
sapply(funcs, function(func) func())

interestingly, identical says they are all unequal, but compare disagrees.

check = function(equal) for (i in 1:4) for (j in i:4+1)

print(equal(envs[[i]], envs[[j]]))

compare seems to cast environments to character; for identical, the docs give an example where environments are compared, but compare fails (i.e., succeeds) miserably (the docs do not warn not to compare environments):

e1 = new.env(parent=emptyenv())
e2 = new.env(parent=emptyenv())
assign("foo", "bar", e1)
compare(e1, e2)
# oops?

back to the original example, how come?


for those curious, try the following in python:

map(lambda func: func(), [lambda: i for i in range(5)]) map(lambda func: func(), (lambda: i for i in range(5)))

R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Mon 17 Nov 2008 - 21:30:25 GMT

Archive generated by hypermail 2.2.0, at Tue 18 Nov 2008 - 02:30:26 GMT.


list of date sections of archive