Get function components of function call inside a function

Viewed 103

Is it possible to retrieve the function components of a function call? That is, is it possible to use as.list(match.call()) on another function call.

The background is, that I want to have a function that takes a function-call and returns the components of said function call.

get_formals <- function(x) {
  # something here, which would behave as if x would be a function that returns
  # as.list(match.call())
}

get_formals(mean(1:10))
# expected to get:
# [[1]]
# mean
#
# $x
# 1:10

The expected result is to have get_formals return as match.call() was called within the supplied function call.

mean2 <- function(...) {
  as.list(match.call())
}
mean2(x = 1:10)
# [[1]]
# mean2
# 
# $x
# 1:10

Another Example

The motivation behind this question is to check if a memoised function already contains the cached values. memoise has the function has_cache() but it needs to be called in a specific way has_cache(foo)(vals), e.g.,

library(memoise)

foo <- function(x) mean(x)
foo_cached <- memoise(foo)

foo_cached(1:10) # not yet cached
foo_cached(1:10) # cached

has_cache(foo_cached)(1:10) # TRUE
has_cache(foo_cached)(1:3) # FALSE

My goal is to log something if the function call is cached or not.

cache_wrapper <- function(f_call) {
  is_cached <- has_cache()() # INSERT SOLUTION HERE
  # I need to deconstruct the function call to pass it to has_cache
  # basically
  # has_cache(substitute(expr)[[1L]])(substitute(expr)[[2L]]) 
  # but names etc do not get passed correctly

  if (is_cached) print("Using Cache") else print("New Evaluation of f_call")
  f_call
}

cache_wrapper(foo_cached(1:10))
#> [1] "Using Cache"     # From the log-functionality
#> 5.5                   # The result from the function-call
3 Answers

You can use match.call() to do argument matching.

get_formals <- function(expr) {
  call <- substitute(expr)
  call_matched <- match.call(eval(call[[1L]]), call)
  as.list(call_matched)
}

get_formals(mean(1:10))

# [[1]]
# mean
# 
# $x
# 1:10

library(ggplot2)
get_formals(ggplot(mtcars, aes(x = mpg, y = hp)))

# [[1]]
# ggplot
# 
# $data
# mtcars
# 
# $mapping
# aes(x = mpg, y = hp)

library(dplyr)
get_formals(iris %>% select(Species))

# [[1]]
# `%>%`
# 
# $lhs
# iris
# 
# $rhs
# select(Species)

Edit: Thanks for @KonradRudolph's suggestion!

The function above finds the right function. It will search in the scope of the parent of get_formals(), not in that of the caller. The much safer way is:

get_formals <- function(expr) {
  call <- substitute(expr)
  call_matched <- match.call(eval.parent(bquote(match.fun(.(call[[1L]])))), call)
  as.list(call_matched)
}

The match.fun() is important to correctly resolve functions that are shadowed by a non-function object of the same name. For example, if mean is overwrited with a vector

mean <- 1:5

The first example of get_formals() will get an error, while the updated version works well.

Here's a way to do it that also gets the default values from the function if you didn't supply all the arguments:

get_formals <- function(call)
{
  f_list <- as.list(match.call()$call)
  func_name <- f_list[[1]]
  p_list <- formals(eval(func_name))
  f_list <- f_list[-1]
  ss <- na.omit(match(names(p_list), names(f_list)))
  if(length(ss) > 0) {
    p_list[na.omit(match(names(f_list), names(p_list)))] <- f_list[ss]
    f_list <- f_list[-ss]
  }
  unnamed <- which(!nzchar(sapply(p_list, as.character)))
  if(length(unnamed) > 0)
  {
    i <- 1
    while(length(f_list) > 0)
    {
      p_list[[unnamed[i]]] <- f_list[[1]]
      f_list <- f_list[-1]
      i <- i + 1
    }
  }
  c(func_name, p_list)
}

Which gives:

get_formals(rnorm(1))
[[1]]
rnorm

$n
[1] 1

$mean
[1] 0

$sd
[1] 1
get_formals(ggplot2::ggplot())
[[1]]
ggplot2::ggplot

$data
NULL

$mapping
aes()

$...


$environment
parent.frame()

To get this to work one level in you could do something like:

foo <- function(f_call) {
  eval(as.call(list(get_formals, call = match.call()$f_call)))
}

foo(mean(1:10))
[[1]]
mean

$x
1:10

$...

This answer is mostly based on Allens answer, but implements Konrads comment regarding the eval and eval.parent functions. Additionally, some do.call is thrown in to finalise the cache_wrapper from the example above:

library(memoise)

foo <- function(x) mean(x)
foo_cached <- memoise(foo)

foo_cached(1:10) # not yet cached
#> [1] 5.5
foo_cached(1:10) # cached
#> [1] 5.5

has_cache(foo_cached)(1:10)
#> [1] TRUE
has_cache(foo_cached)(1:3)
#> [1] FALSE

# As answered by Allen with Konrads comment
get_formals <- function(call) {
  f_list <- as.list(match.call()$call)
  func_name <- f_list[[1]]
  # changed eval to eval.parent as suggested by Konrad...
  p_list <- formals(eval.parent(eval.parent(bquote(match.fun(.(func_name))))))
  f_list <- f_list[-1]
  ss <- na.omit(match(names(p_list), names(f_list)))
  if(length(ss) > 0) {
    p_list[na.omit(match(names(f_list), names(p_list)))] <- f_list[ss]
    f_list <- f_list[-ss]
  }
  unnamed <- which(!nzchar(sapply(p_list, as.character)))
  if(length(unnamed) > 0) {
    i <- 1
    while(length(f_list) > 0) {
      p_list[[unnamed[i]]] <- f_list[[1]]
      f_list <- f_list[-1]
      i <- i + 1
    }
  }
  c(func_name, p_list)
}

# check if the function works with has_cache
fmls <- get_formals(foo_cached(x = 1:10))
do.call(has_cache(eval(parse(text = fmls[1]))),
        fmls[2])
#> [1] TRUE


# implement a small wrapper around has_cache that reports if its using cache
cache_wrapper <- function(f_call) {
  fmls <- eval(as.call(list(get_formals, call = match.call()$f_call)))
  is_cached <- do.call(has_cache(eval(parse(text = fmls[1]))),
                       fmls[2])
  if (is_cached) print("Using Cache") else print("New Evaluation of f_call")
  f_call
}

cache_wrapper(foo_cached(x = 1:10))
#> [1] "Using Cache"
#> [1] 5.5

cache_wrapper(foo_cached(x = 1:30))
#> [1] "New Evaluation of f_call"
#> [1] 5.5
Related