[R] undo compile? (or: remove bytecode from closure)

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Mon Jul 16 12:58:31 CEST 2018


On 16/07/2018 5:31 AM, Rui Barradas wrote:
> Hello,
> 
> Maybe the following is not the recommended way but it works
> (and I believe makes sense).
> 
> 
> f <- function(){}
> formals(f) <- formals(fc)
> body(f) <- body(fc)

That's not quite right:  it might lose the environment of fc, if it 
isn't the environment where this took place.  But a simpler solution is just

f <- fc
body(f) <- body(f)

because any assignment to the body of a function causes the bytecode to 
be dropped.

Both of our approaches will also cause the source references to be 
dropped.  If you want to save those, you need more steps:

f <- fc
body(f) <- body(f)
attr(f, "srcref") <- getSrcref(fc)

Duncan Murdoch

> 
> f
> #function (x)
> #{
> #  x <- x + 1
> #  pi * x
> #}
> 
> f(1)
> #[1] 6.283185
> 
> 
> Hope this helps,
> 
> Rui Barradas
> 
> Às 03:25 de 16-07-2018, Benjamin Tyner escreveu:
>> Hi
>>
>> Given a closure which has been compiled, what's the recommended way to
>> recover the original? For example,
>>
>>       > f <- function(x) x+1
>>       > fc <- cmpfun(f)
>>       > rm(f)
>>       > fc
>>       function(x) x+1
>>       <bytecode: 0x41d9228>
>>
>> what's the best way to recover f from fc ?
>>
>> Regards
>>
>> Ben
>>
>> ______________________________________________
>> 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.
> 
> ______________________________________________
> 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