Nushell
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
GitHub
Get Nu!
Getting Started
  • The Nushell Book
  • Command Reference
  • Cookbook
  • Language Reference Guide
  • Contributing Guide
Blog
  • English
  • 中文
  • Deutsch
  • Français
  • Español
  • 日本語
  • Português do Brasil
  • Русский язык
GitHub
  • Categories

    • Bits
    • Bytes
    • Chart
    • Conversions
    • Core
    • Database
    • Dataframe
    • Dataframe Or Lazyframe
    • Date
    • Debug
    • Default
    • Env
    • Experimental
    • Expression
    • Filesystem
    • Filters
    • Formats
    • Generators
    • Hash
    • History
    • Lazyframe
    • Math
    • Misc
    • Network
    • Path
    • Platform
    • Plugin
    • Prompt
    • Random
    • Removed
    • Shells
    • Strings
    • System
    • Viewers

generate for generators

Generate a list of values by successively invoking a closure.

Signature

> generate {flags} (closure) (initial)

Parameters

  • closure: Generator function.
  • initial: Initial value.

Input/output types:

inputoutput
list<any>list<any>
nothinglist<any>
rangelist<any>
tablelist<any>

Examples

Generate a sequence of numbers

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

Generate a continuous stream of Fibonacci numbers

> generate {|fib| {out: $fib.0, next: [$fib.1, ($fib.0 + $fib.1)]} } [0, 1]

Generate a continuous stream of Fibonacci numbers, using default parameters

> generate {|fib=[0, 1]| {out: $fib.0, next: [$fib.1, ($fib.0 + $fib.1)]} }

Generate a running sum of the inputs

> 1..5 | generate {|e, sum=0| let sum = $e + $sum; {out: $sum, next: $sum} }
╭───┬────╮
│ 0 │  1 │
│ 1 │  3 │
│ 2 │  6 │
│ 3 │ 10 │
│ 4 │ 15 │
╰───┴────╯

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.

Additionally, if an input stream is provided, the generator closure accepts two arguments. On each invocation an element of the input stream is provided as the first argument. The second argument is the next value from the last invocation. In this case, generation also stops when the input stream stops.