Created
March 21, 2019 10:34
-
-
Save moodymudskipper/3f3a1ab918a6a39b591642179475ae56 to your computer and use it in GitHub Desktop.
infix operators on steroids
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
Not sure exactly how useful that would be but that'd be a fun small package. | |
The following `infix` function parses an expression containing | |
multiple infix operators so we can do things like `infix(x %is_between% y %and% z)`, i.e an "infix operation" with more than 2 parameters. | |
See example. | |
The name `infix` is not great. | |
``` | |
infix <- function(x) { | |
x <- substitute(x) | |
args <- alist() | |
funs <- character(0) | |
while(length(x) > 1 && grepl("^\\%.*\\%$",deparse(x[[1]]))){ | |
args <- c(x[[3]], args) | |
funs <- c(gsub("%","",deparse(x[[1]]),fixed=TRUE),funs) | |
x <- x[[2]] | |
} | |
fun <- paste(funs, collapse="/") | |
args <- c(x, args) | |
eval.parent(rlang::expr((!!as.name(fun))(!!!args))) | |
} | |
# define function using "/" separator | |
`is_between/and` <- function(x,y,z) {between(x,y,z)} | |
# infix will parse the expression and call the relevant function | |
x <- 5 | |
y <- 1 | |
z <- 10 | |
infix(x %is_between% y %and% z) | |
# [1] TRUE | |
x <- 12 | |
infix(x %is_between% y %and% z) | |
# [1] FALSE | |
``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think regular infix operators like
%in%
can still be used if the expression is wrapped insideforce
oridentity
, but it isn't tested.