Skip to content

Commit

Permalink
capturing closures
Browse files Browse the repository at this point in the history
  • Loading branch information
mailund committed Feb 25, 2019
1 parent f819c72 commit 54a5453
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Expand Up @@ -2,5 +2,6 @@

export(can_loop_transform)
export(can_loop_transform_)
export(capture_closure)
export(loop_transform)
import(foolbox)
19 changes: 19 additions & 0 deletions R/loop-transformation.R
Expand Up @@ -106,6 +106,10 @@ try_loop_transform <- function(fun) {
call_arguments <- rlang::call_args(expr)
fun_call_allowed <- topdown

if (call_name == "function") {
skip(expr) # whatever we do when defining a functio won't be executed here
}

if (call_name == fun_name) {
if (!fun_call_allowed) {
warn_msg <- simpleWarning(
Expand Down Expand Up @@ -389,3 +393,18 @@ loop_transform <- function(fun, byte_compile = TRUE, set_srcref = TRUE) {

result
}

#' Captures the closure in a function environment
#'
#' This is necessary to implement continuation-passing-style
#' tail-recursion.
#'
#' @param .func The function to capture a closure for.
#'
#' @export
capture_closure <- function(.func) {
captured_env <- rlang::env_clone(rlang::caller_env())
environment(.func) <- captured_env
.func
}

15 changes: 15 additions & 0 deletions man/capture_closure.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 54a5453

Please sign in to comment.