with_block: Turn a function into one that accepts a block, ruby-style.

Description Usage Arguments Value Examples

View source: R/with_block.R

Description

Turn a function into one that accepts a block, ruby-style.

Usage

1

Arguments

fn

function. The function to convert into a block-accepting function. When calling yield() from within the function, the block will be substituted instead.

Value

a function with one additional argument called "_block" that will store an expression to evaluate using yield() from within the body of fn. Additional "arguments" can be passed to yield which will be injected into the lexical scope of the evaluation.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
blocked_fn <- with_block(function(x, y) x + y + yield())
stopifnot(identical(blocked_fn(1, 2, { 3 + 4 }), 10))

assign_names <- with_block(function(x) {
 setNames(x, vapply(x, function(y) paste0("element_", yield(name = y)), character(1)))
})
stopifnot(identical(assign_names(letters[1:5], { toupper(name) }),
  list(element_A = 'a', element_B = 'b', element_C = 'c',
    element_D = 'd', element_E = 'e')))

maybe_block <- with_block(function() { list(1, if (block_given()) yield()) })
stopifnot(identical(maybe_block(2), list(1, 2)) && identical(maybe_block(), list(1)))

robertzk/productivus documentation built on July 23, 2019, 2:22 p.m.