rlang: minimal Haskell where clause in R
A minimal example of a Haskell where clause implemented in R:
library(rlang)
`%where%` <- function(lhs, rhs) {
rhs_ex <- enexpr(rhs)
lhs_ex <- enexpr(lhs)
eval(rhs_ex)
eval(lhs_ex)
}
sum_1 <- sum(x, y) %where% {
x <- 1;
y <- 2;
}
sum_1 == 3
#> [1] TRUE
Variables bound within where are not bound in the global environment.
exists("x")
#> [1] FALSE
exists("y")
#> [1] FALSE
Variables bound within where mask those in global environment.
x <- 3
y <- 4
sum_2 <- sum(x, y) %where% {
x <- 1;
y <- 2;
}
sum_2 == 3
#> [1] TRUE
Variable in the global enviroment remain unchanged.
x == 3
#> [1] TRUE
y == 4
#> [1] TRUE
If variables are not bound within where, normal variable look-up.
z <- 3
sum_3 <- sum(x, y, z) %where% {
x <- 1;
y <- 2;
}
sum_3 == 6
#> [1] TRUE
As expected, undefined variables throw an error.
sum_4 <- sum(x, y, a) %where% {
x <- 1;
y <- 2;
}
#> Error in eval(lhs_ex): object 'a' not found
Functions can be defined within where.
sum_5 <- sum(f(x), f(y)) %where% {
x <- 1;
y <- 2;
f <- as_function(~.x + 1)
}
sum_5 == 5
#> [1] TRUE
exists("f")
#> [1] FALSE
Created on 2020-03-29 by the reprex package (v0.3.0)