Created
December 2, 2016 21:35
-
-
Save jrnold/da51ec2dbd0aa748221dc17e3bf07e36 to your computer and use it in GitHub Desktop.
Alternative R compose function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.