Created
February 12, 2016 15:17
-
-
Save klmr/35a13344080e71bf8c34 to your computer and use it in GitHub Desktop.
Haskell-like list comprehension for R
This file contains hidden or 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
# Dummy object, only required for name resolution. | |
set = structure(list(), class = 'set') | |
print.set = function (x, ...) invisible(x) | |
`[.set` = function (set, expr, filter) { | |
expr = substitute(expr) | |
filter = substitute(filter) | |
stopifnot(identical(expr[[1]], quote(`<-`))) | |
stopifnot(identical(expr[[2]][[1]], quote(`|`))) | |
map = expr[[2]][[2]] | |
gen = expr[[3]] | |
var = expr[[2]][[3]] | |
stopifnot(length(var) == 1 && is.name(var)) | |
var = deparse(var, backtick = TRUE) | |
range = eval.parent(gen) | |
closure = function (formals, body, envir) | |
eval(call('function', as.pairlist(formals), body), envir) | |
formals = as.pairlist(setNames(c(quote(expr = )), var)) | |
f = closure(formals, filter, parent.frame()) | |
g = closure(formals, map, parent.frame()) | |
sapply(Filter(f, range), g) | |
} | |
# Example: | |
set[x + 1 | x <- 1 : 10, x %% 2 == 0] | |
# [1] 3 5 7 9 11 | |
# Implementing multi-variable list comprehension left as exercise for the reader. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment