Identifying whether a named function was supplied as function argument

28 views Asked by At

As part of a project I've been working on I would like to allow the user to return a summary of various inputs of a nested object structure. A part of the objects are used as containers or formatters, while the remainders are used to parse other input.

Basically the summary would be formatting 'name', 'function type/name' and some other descriptors. But I've stumbled a bit over the second part, the 'function type/name'.

How would one identify whether a named function or lambda-like (unnamed) function was provided as argument to a function?

A few idea's I had for solving the problem was substituting the input (assuming it is not missing) and checking whether the input was a name or call

f <- function(x)
  substitute(x)
class(f(sum))
[1] "name"
class(f(function(x) x**2))
[1] "call"

But this is incomplete as a function call could still be considered a named

f(sum(x))
[1] "call"

In it's simplest format I'd be searching for the function to return "named function" and "unnamed function" searching through loaded namespaces. Eg. sum and sum(x) is a named function, while function(x) x**2 is an unnamed function.

1

There are 1 answers

0
Rui Barradas On BEST ANSWER

Maybe the following can give an idea of what to do, if I understand the question correctly.

f <- function(x){
  flag <- is.function(x)
  y <- as.character(substitute(x))[1]
  if(flag){
    i <- grepl("function", y) + 1L
    c("named function", "unnamed function")[i]
  } else {
    #msg <- paste(sQuote(y), "is not a function.")
    #message(msg)
    flag
  }
}

f(sum)
#[1] "named function"
f(sum(x))
#[1] FALSE
f(function(x) x**2)
#[1] "unnamed function"