From 54a545359ea9b8de8da66d1e1e8f6b4b5e396f75 Mon Sep 17 00:00:00 2001 From: Thomas Mailund Date: Mon, 25 Feb 2019 15:36:53 +0100 Subject: [PATCH] capturing closures --- NAMESPACE | 1 + R/loop-transformation.R | 19 +++++++++++++++++++ man/capture_closure.Rd | 15 +++++++++++++++ 3 files changed, 35 insertions(+) create mode 100644 man/capture_closure.Rd diff --git a/NAMESPACE b/NAMESPACE index 87e5289..5b59f6e 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -2,5 +2,6 @@ export(can_loop_transform) export(can_loop_transform_) +export(capture_closure) export(loop_transform) import(foolbox) diff --git a/R/loop-transformation.R b/R/loop-transformation.R index 280e409..a4644a0 100644 --- a/R/loop-transformation.R +++ b/R/loop-transformation.R @@ -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( @@ -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 +} + diff --git a/man/capture_closure.Rd b/man/capture_closure.Rd new file mode 100644 index 0000000..bfe6325 --- /dev/null +++ b/man/capture_closure.Rd @@ -0,0 +1,15 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/loop-transformation.R +\name{capture_closure} +\alias{capture_closure} +\title{Captures the closure in a function environment} +\usage{ +capture_closure(.func) +} +\arguments{ +\item{.func}{The function to capture a closure for.} +} +\description{ +This is necessary to implement continuation-passing-style +tail-recursion. +}