Skip to content

Instantly share code, notes, and snippets.

@jrnold
Created December 2, 2016 21:35
Show Gist options
  • Save jrnold/da51ec2dbd0aa748221dc17e3bf07e36 to your computer and use it in GitHub Desktop.
Save jrnold/da51ec2dbd0aa748221dc17e3bf07e36 to your computer and use it in GitHub Desktop.
Alternative R compose function
library(purrr)
compose2 <- function (...) {
fs <- lapply(list(...), match.fun)
n <- length(fs)
last <- fs[[n]]
rest <- fs[-n]
newf <- function(...) {
cl <- match.call()
cl[[1L]] <- last
out <- eval(cl)
for (f in rev(rest)) {
out <- f(out)
}
out
}
formals(newf) <- formals(last)
newf
}
#not_null <- compose2(`!`, is.null)
#not_null(4)
#not_null(NULL)
add1 <- function(x) x + 1
compose(add1, add1)(8)
formals(add1)
@jrnold
Copy link
Author

jrnold commented Dec 2, 2016

Unlike purrr::compose, the returned function has the same formals as the last (innermost) function. This is useful for autocompletion and documentation of the new function. However, since primitives don't have formals, this isn't completely general.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment