List.Generate

Syntax

List.Generate(initial as function, condition as function, next as function, optional selector as nullable function) as list

About

Generates a list of values using the provided functions. The initial function generates a starting candidate value, which is then tested against condition. If the candidate value is approved, then it's returned as part of the resulting list, and the next candidate value is generated by passing the newly approved value to next. Once a candidate value fails to match condition, the list generation process stops. An optional parameter, selector, may also be provided to transform the items in the resulting list.

Example 1

Create a list by starting at ten, repeatedly decrementing by one, and ensuring each item is greater than zero.

Usage

List.Generate(() => 10, each _ > 0, each _ - 1)

Output

{10, 9, 8, 7, 6, 5, 4, 3, 2, 1}

Example 2

Generate a list of records containing x and y, where x is a value and y is a list. x should remain less than 10 and represent the number of items in the list y. After the list is generated, return only the x values.

Usage

List.Generate(
    () => [x = 1, y = {}],
    each [x] < 10,
    each [x = List.Count([y]), y = [y] & {x}],
    each [x]
)

Output

{1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9}