[R] Modificatio of function body within a function

Bert Gunter bgunter@4567 @end|ng |rom gm@||@com
Fri Apr 1 23:12:28 CEST 2022


Heh ... These self-referential constructs are certainly puzzles...

Does this help:

fun1 <- function() {
   1
   body(fun1)[[2]] <<- 'one'
   'hi'
}

> fun1
function() {
   1
   body(fun1)[[2]] <<- 'one' ## note the double '<<" assigning to the parent env
   'hi'
}

> fun1()
[1] "hi"

> fun1
function ()
{
    "one" ## the change was made
    body(fun1)[[2]] <<- "one"
    "hi"
}

The point is that assignments within a function occur *within* the
function environment unless otherwise specified (either by <<- or the
use of the 'environment' argument in 'body<-'()  ). This is, of
course, central to the functional programming paradigm of no side
effects (unless explicitly invoked).

NOTE: Correction to this requested if this is wrong in any way!!

Cheers,
Bert




Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )

Bert Gunter

"The trouble with having an open mind is that people keep coming along
and sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )


On Fri, Apr 1, 2022 at 12:50 PM Grzegorz Smoliński
<g.smolinski1 using gmail.com> wrote:
>
> Hi,
>
> I'm working on a presentation regarding the modification of the
> function body on-the-fly and just discovered something I don't
> understand. I would like to modify a body of the function within a
> function, but I see that it is possible only when explicitly referring
> to the environment where the function is defined:
>
> fun1 <- function() {
>   1
>   body(fun1)[[2]] <- "one"
> }
> fun1()
> body(fun1)
> #> {
> #>     1
> #>     body(fun1)[[2]] <- "one"
> #> }
>
> fun2 <- function() {
>   2
>   env <- environment(fun2)
>   body(env$fun2)[[2]] <- "two"
> }
> fun2()
> body(fun2)
> #> {
> #>     "two"
> #>     env <- environment(fun2)
> #>     body(env$fun2)[[2]] <- "two"
> #> }
>
> Can I get some explanation or some links / articles about this,
> please? I thought it won't be a difference and I should be able to
> modify a function body also in the first case, because I'm changing
> something in the parent environment being in the child environment.
>
> Best regards,
>
> Grzegorz
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.



More information about the R-help mailing list