generator: Construct a new generator

Description Usage Arguments Details Examples

View source: R/generator.R

Description

A generator is a function that contains a mutable state. Calls to the function change the state and return a value in a series.

Usage

1
generator(.start, .update, .yield = identity)

Arguments

.start

A vector that describes the initial state of the generator

.update

A function or formula controlling how the state changes over time

.yield

A function or formula controlling how a series is returned from the state

Details

Syntax sugar is borrowed from purrr, allowing for the creation of anonymous functions using formulas. Unlike purrr, this package uses state as the key pronoun for all functions.

Examples

1
2
3
4
5
6
7
8
# The simplest form of generator is a counter
my_counter <- generator(0, ~ state + 1)

# More complicated generators also need a yield.
my_fib <- generator(c(0, 1),
                    ~ c(state[2], sum(state)),
                    ~ state[1])
take(my_fib, 5)

michaelquinn32/generators documentation built on May 22, 2019, 9:52 p.m.