Skip to content

Instantly share code, notes, and snippets.

@FrankPortman
Last active May 25, 2017 19:16
Show Gist options
  • Save FrankPortman/2aac330c6f293e66e43ae4e89bb86e65 to your computer and use it in GitHub Desktop.
Save FrankPortman/2aac330c6f293e66e43ae4e89bb86e65 to your computer and use it in GitHub Desktop.
compose_right_to_left <- function(funs) function(x) Reduce(function(y, f) f(y), funs, x)
some_composition <- compose_right_to_left(list(cumsum, sqrt, log))
# cumsum(sqrt(log(16:35))), these are all vectorized and return length n output
some_composition(16:35)
# Creates a function that takes in a list of functions and returns a function
# that applies those functions to an input argument 'value'. These functions can `reduce` (sum)
# or apply a potentially vectorized operation (`log`, `sqrt`, etc) in whatever order you want.
# Ex list(sum, sqrt, log) will take log of all entries, then sqrt of that result and finally sum up to one number
compose_right_to_left <- function(funs) {
function(value) {
Reduce(function(y, f) f(y), funs, value)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment