unfold for generators

Generate a list of values by successively invoking a closure.

Signature

> unfold {flags} (initial) (closure)

Parameters

  • initial: initial value
  • closure: generator function

Input/output types:

input output
list<any> list<any>
nothing list<any>

Examples

Generate a sequence of numbers

> unfold 0 {|i| if $i <= 10 { {out: $i, next: ($i + 2)} }}
╭───┬────╮
│ 0 │  0 │
│ 1 │  2 │
│ 2 │  4 │
│ 3 │  6 │
│ 4 │  8 │
│ 5 │ 10 │
╰───┴────╯

Generate a stream of fibonacci numbers

> unfold [0, 1] {|fib| {out: $fib.0, next: [$fib.1, ($fib.0 + $fib.1)]} } | first 10
╭───┬────╮
│ 0 │  0 │
│ 1 │  1 │
│ 2 │  1 │
│ 3 │  2 │
│ 4 │  3 │
│ 5 │  5 │
│ 6 │  8 │
│ 7 │ 13 │
│ 8 │ 21 │
│ 9 │ 34 │
╰───┴────╯

Notes

The generator closure accepts a single argument and returns a record containing two optional keys: 'out' and 'next'. Each invocation, the 'out' value, if present, is added to the stream. If a 'next' key is present, it is used as the next argument to the closure, otherwise generation stops.