Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get currently called function to write anonymous recursive function

Tags:

r

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.

like image 523
Jeroen Ooms Avatar asked Oct 31 '13 18:10

Jeroen Ooms


People also ask

How do you call an anonymous recursive function?

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.

How do you declare an anonymous 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... } )

Can an anonymous function be recursive in Python?

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.


2 Answers

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
like image 141
agstudy Avatar answered Sep 29 '22 21:09

agstudy


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.

like image 32
sds Avatar answered Sep 29 '22 19:09

sds