[R] unexpected results with higher-order functions and lapply

2010-02-14 Thread Jyotirmoy Bhattacharya
I want to use lapply and a function returning a function in order to build a
list of functions.

 genr1 - function(k) {function() {k}}
 l1 - lapply(1:2,genr1)
 l1[[1]]()
[1] 2

This was unexpected. I had expected the answer to be 1, since that is the
value k should be bound to when genr1 is applied to the first element of
1:2.

By itself genr1 seems to work fine.
 genr1(5)()
[1] 5

I defined a slightly different higher-order function:
 genr2 - function(k) {k;function() {k}}
 l2 - lapply(1:2,genr2)
 l2[[1]]()
[1] 1

This gives the answer I expected.

Now I am confused. The function returned by genr2 is exactly the same
function that was being returned by genr1. Why should evaluating k make a
difference?

I am using R 2.9.2 on Ubuntu Linux.

Jyotirmoy Bhattacharya

[[alternative HTML version deleted]]

__
R-help@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.


Re: [R] unexpected results with higher-order functions and lapply

2010-02-14 Thread baptiste auguie
Hi,

I believe it's lazy evaluation. See ?force

HTH,

baptiste

On 14 February 2010 20:32, Jyotirmoy Bhattacharya
jyotir...@jyotirmoy.net wrote:
 I want to use lapply and a function returning a function in order to build a
 list of functions.

 genr1 - function(k) {function() {k}}
 l1 - lapply(1:2,genr1)
 l1[[1]]()
 [1] 2

 This was unexpected. I had expected the answer to be 1, since that is the
 value k should be bound to when genr1 is applied to the first element of
 1:2.

 By itself genr1 seems to work fine.
 genr1(5)()
 [1] 5

 I defined a slightly different higher-order function:
 genr2 - function(k) {k;function() {k}}
 l2 - lapply(1:2,genr2)
 l2[[1]]()
 [1] 1

 This gives the answer I expected.

 Now I am confused. The function returned by genr2 is exactly the same
 function that was being returned by genr1. Why should evaluating k make a
 difference?

 I am using R 2.9.2 on Ubuntu Linux.

 Jyotirmoy Bhattacharya

        [[alternative HTML version deleted]]

 __
 R-help@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.


__
R-help@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.