Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lazy pipe #11

Open
moodymudskipper opened this issue Nov 8, 2019 · 0 comments
Open

lazy pipe #11

moodymudskipper opened this issue Nov 8, 2019 · 0 comments

Comments

@moodymudskipper
Copy link
Owner

We can reasonably easily implement a lazy pipe, there's just a weird issue with functional sequences :

library(fastpipe)

`%~>%` <- function (lhs, rhs) 
{
  if (globals$master) {
    sc <- sys.call()
    return(eval_slaves(sc, parent.frame()))
  }
  lhs_call <- substitute(lhs)
  rhs_call <- insert_dot(substitute(rhs))

  if (lhs_call == quote(.)) {
    bare_pipe <- attr(sys.function(), "bare_version")
    res <- call(bare_pipe, lhs_call, rhs_call)
    fs_on()
    return(res)
  }

  if (globals$is_fs) {
    bare_pipe <- attr(sys.function(), "bare_version")
    res <- call(bare_pipe, lhs, rhs_call)
    return(res)
  }

  new_env <- new.env()
  eval(bquote(
    delayedAssign(".", .(lhs_call),eval.env = parent.frame(), assign.env = new_env)))
  eval(rhs_call, envir = new_env, enclos = parent.frame())
}

`%~>>%` <- function (lhs, rhs) {
  lhs_call <- substitute(lhs)
  rhs_call <- substitute(rhs)
  new_env <- new.env()
  eval(bquote(
    delayedAssign(".", .(lhs_call),eval.env = parent.frame(), assign.env = new_env)))
  eval(rhs_call, envir = new_env, enclos = parent.frame())
}

class(`%~>%`) <- class(`%~>>%`) <- "fastpipe"
attr(`%~>%`, "bare_version") <- "%~>>%"

environment(`%~>%`) <- as.environment(asNamespace("fastpipe"))
environment(`%~>>%`) <- as.environment(asNamespace("fastpipe"))


stop("!") %>%
  tryCatch(error = function(e) "An error")
#> Error in force(lhs): !

stop("!") %~>%
  tryCatch(error = function(e) "An error")
#> [1] "An error"

stop("!") %~>>%
  tryCatch(error = function(e) "An error")
#> [1] "An error"

"!" %>% stop() %~>%
  tryCatch(error = function(e) "An error") %>%
  toupper()
#> [1] "AN ERROR"

fs <- . %>% stop() %~>% 
  tryCatch(error = function(e) "An error") %>%
  toupper()

# this is weird, maybe just a namespace thing, try in package
fs
#> function (.) 
#> . %>>% stop(.) %>>% toupper(.)

# what if it had worked ?
fs <- function(.)
  . %>>% stop(.) %~>>% 
  tryCatch(error = function(e) "An error") %>>%
  toupper(.)

# then as expected
fs("!")
#> [1] "AN ERROR"

msg <- "old"
delayedAssign("x", stop("hi!"))
substitute(x) # shows only 'x', as it is in the global env.
#> x
msg <- "new!"
x # new!
#> Error in eval(expr, envir, enclos): hi!

Created on 2019-11-08 by the reprex package (v0.3.0)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant