Skip to content
Back to formatted view

Raw Message

Message-ID: <971536df0905200500y234baa02l5d2c8b6777a8a414@mail.gmail.com>
Date: 2009-05-20T12:00:09Z
From: Gabor Grothendieck
Subject: Functions returning functions
In-Reply-To: <4A13EE28.1080206@idi.ntnu.no>

On Wed, May 20, 2009 at 7:48 AM, Wacek Kusnierczyk
<Waclaw.Marcin.Kusnierczyk at idi.ntnu.no> wrote:
> Paulo Grahl wrote:
>> Dear All:
>>
>> I have a question regarding the behavior of functions.
>> Say I define a function that returns another function :
>> A <- function(parameters) {
>> ? ? ?# calculations w/ parameters returning 'y'
>> ? ? ?tmpf <- function(x) { # function of 'y' }
>> ? ? ?return(tmpf)
>> }
>>
>> The value of the parameters are stored in an environment local to the
>> function.
>
> consider this example:
>
> ? ?foo = function(a, b)
> ? ? ? function(c)
> ? ? ? ? ?if (c) a else b
>
> ? ?x = 1
> ? ?y = 2
> ? ?bar = foo(x, y)
>
> ? ?bar(TRUE)
> ? ?# 1
> ? ?x = 0
> ? ?bar(TRUE)
> ? ?# 1, not 0
>
> ? ?y = 0
> ? ?bar(FALSE)
> ? ?# 0, not 2
>

The last one is due to lazy evaluation.  Try
repeating it with this variation:

   foo2 = function(a, b) {
	  force(a); force(b)
          function(c) if (c) a else b
   }

which forces a and b to be evaluated right away.