How can I get the current function within a function for recursive applying? Here is a trivial example:
myfun <- function(x) {
if(is.list(x)){
lapply(x, myfun)
} else {
length(x)
}
}
I would like to make it anonymous instead, however I don't know how to tell lapply
to use the current function when it has no name. I tried Recall
but that doesn't work:
(function(x) {
if(is.list(x)){
lapply(x, Recall)
} else {
length(x)
}
})(cars)
Also match.call()[[1]]
doesn't help for anonymous functions.
Anonymous recursive function is a type of recursion in which function does not explicitly call another function by name. This can be done either comprehensively, by using a higher order function passing in a function as an argument and calling that function.
An anonymous function can also have multiple arguments, but only one expression. We may also declare anonymous function using arrow function technique which is shown below: ( () => { // Function Body... } )
Anonymous recursion via explicitly passing functions as arguments is possible in any language that supports functions as arguments, though this is rarely used in practice, as it is longer and less clear than explicitly recursing by name.
It is sys.function(0)
, for example to compute the square of a list recursively :
(function(x) {
if(length(x)>2){
lapply(x,sys.function(0))
} else {
x^2
}
})(list(1,2,3))
[[1]]
[1] 1
[[2]]
[1] 4
[[3]]
[1] 9
What you are looking for is, I think, sys.function
:
> (function() print(sys.function(1)))()
function() print(sys.function(1))
Recall
actually says:
local
for another way to write anonymous recursive functions.
The idea is that you define the name locally:
local(myfun <- function(...) { ... myfun(...) ... })
and it is not defined outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With