foldc: Consume a fold a generator, producing a scalar

Description Usage Arguments See Also Examples

View source: R/fold.R

Description

Generate iterations of a generator up to its limit, reducing the values using a binary function.

Usage

1
foldc(.generator, .FUN, ..., .start = 0)

Arguments

.generator

A function with the class generator

.FUN

A binary fold function to reduce the generator to a single value

...

Additional arguments to .FUN

.start

The starting value for the reduction

See Also

foldn and consume

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# Sum of numbers from 1 to 10
counter <- generator(0, function (state) state + 1)

counter %>%
  limit(~ state <= 10) %>%
  foldc(`+`)

# Version of Project Euler 2: Sum of even Fibonacci numbers
fib <- generator(c(0, 1),
                 ~ c(state[2], sum(state)),
                 ~ state[1])

fib %>%
  keep(~ state %% 2 == 0) %>%
  limit(~ state < 400) %>%
  foldc(`+`)

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