Last active
December 17, 2017 10:19
-
-
Save lionel-/ae241acf956e6e03942deaefb7ef685a to your computer and use it in GitHub Desktop.
Unquoting RHS of magrittr pipe with quosure support
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
# Actually does not work because quosured magrittr pronouns are not | |
# evaluated in the right environment | |
library("magrittr") | |
library("rlang") | |
# Anticipate renaming of `quo_is_lang()` in rlang | |
quo_is_call <- quo_is_lang | |
quo_call_smash <- function(quo) { | |
if (!quo_is_call(quo)) { | |
abort("Expected quosured call") | |
} | |
expr <- duplicate(get_expr(quo), shallow = TRUE) | |
env <- get_env(quo) | |
rest <- expr | |
while (!is_null(rest)) { | |
node_poke_car(rest, new_quosure(node_car(rest), env)) | |
rest <- node_cdr(rest) | |
} | |
expr | |
} | |
`%foo%` <- function(lhs, rhs) { | |
rhs <- enquo(rhs) | |
lhs <- enquo(lhs) | |
if (quo_is_call(rhs)) { | |
eval_tidy(quo(`%>%`(!!lhs, !!quo_call_smash(rhs)))) | |
} else { | |
eval_tidy(quo(`%>%`(!!lhs, (!!rhs)()))) | |
} | |
} | |
(!!letters) %foo% toupper | |
letters %foo% toupper() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment