Skip to content
Back to formatted view

Raw Message

Message-ID: <20190124173901.7881f386@parabola>
Date: 2019-01-24T14:39:49Z
From: Ivan Krylov
Subject: Function in default parameter value closing over variables defined later in the enclosing function
In-Reply-To: <fc41f3a2-dff3-ec52-8181-a6eb936abf5c@gmail.com>

Dear Jan & Duncan,

Thanks for your replies!

On Wed, 23 Jan 2019 09:56:25 -0500
Duncan Murdoch <murdoch.duncan at gmail.com> wrote:

> Defaults of variables are evaluated in the evaluation frame of the
> call. So the inside() function is created in the evaluation frame,
> and it's environment will be that frame.
 
> When it is called it will create a new evaluation frame (empty in
> your example), with a parent being its environment, i.e. the
> evaluation frame from when it was created, so it will be able to see
> your secret variable.

Nice explanation about closures in R inheriting not only their
explicitly captured variables, but whole environments of evaluation
(not stack) frames where they have been created.

> in my opinion it would be fine to write it as
> 
>   outside <- function(inside = defaultInsideFn) {
>      defaultInsideFn <- function() print(secret)
>      secret <- 'secret'
>      inside()
>   }

I like this idea; I'm going to use it.

-- 
Best regards,
Ivan