KScript docs
EN

list fields and methods

Lists such as [1, 2, 3]. Methods that change a list return a new one.

A list holds values in order: ['tea', 'milk', 'juice'], [3, 7, 9], or records such as [{ name: 'Ada', age: 36 }]. The first item is at index 0, and a negative index counts from the end, so $drinks[-1] is the last item.

List methods never change the list they are called on. A method such as ->push() or ->sort() gives a new list, so you keep the result in a variable or chain the next method onto it:

<let name="drinks" value="['tea', 'milk']" />
<let name="more" value="$drinks->push('juice')" />
<echo value="$drinks" /> <!-- ['tea', 'milk'] because ->push() gives a new list and leaves this one alone -->
<echo value="$more" /> <!-- ['tea', 'milk', 'juice'] -->
$drinks = ['tea', 'milk']
$more = $drinks->push('juice')
echo $drinks   // ['tea', 'milk'] because ->push() gives a new list and leaves this one alone
echo $more     // ['tea', 'milk', 'juice']

Methods that take a function call it once for each item. The function gets the item first and, if you ask for it, the item's index second: fn(drink) => ... or fn(drink, index) => .... The hint in the editor shows what a method passes, such as ->reduce(fn(total, item), initial?). Where you only want a field or a method of each item, write it with a dot instead of a whole function: ->map(.name) is ->map(fn(person) => $person.name), and ->filter(.is_empty()) is ->filter(fn(text) => $text->is_empty()).

Find out about a list: count · count_of · is_empty · contains · index_of · any · all

Take items out: first · last · at · find · max · min · take · skip · slice · take_while · skip_while · pluck

Keep some items: filter · reject · only · without · partition · unique · difference · intersect · union

Change every item: map · flat_map · each

Add, remove and reorder: push · prepend · insert · replace_at · remove · remove_at · pop · reverse · sort · rotate

Combine into one value: sum · product · average · reduce · scan · join · common · count_by

Group and reshape: group_by · to_map · chunk · window · split · flatten · zip · cells · positions_of · shapes · combinations · permutations

A field is a plain fact about the value, read with a dot and no brackets: $value.name. A method takes arguments or does work, and is called with ->: $value->name(arguments), or with the value piped in: $value |> name(arguments).

From KScript.Core

#list->all(fn(item, index?)) → bool

True when fn is true for every item.

->all(fn(item, index?)) is true when the function is true for every item. It stops at the first item that fails. An empty list gives true, because no item fails:

<let name="scores" value="[72, 85, 91]" />
<echo value="$scores->all(fn(score) => $score >= 50)" /> <!-- true because every score is at least 50 -->
<echo value="$scores->all(fn(score) => $score >= 80)" /> <!-- false because 72 is below 80 -->
<echo value="[]->all(fn(score) => $score >= 80)" /> <!-- true because there is no score to fail -->
$scores = [72, 85, 91]
echo $scores->all(fn(score) => $score >= 50)   // true because every score is at least 50
echo $scores->all(fn(score) => $score >= 80)   // false because 72 is below 80
echo []->all(fn(score) => $score >= 80)        // true because there is no score to fail
ParameterTakes
fn requiredfn
Example
<echo>{ [3, 8, 1]->all(fn(n) => $n > 0) }</echo>
echo [3, 8, 1]->all(fn(n) => $n > 0)

#list->any(fn(item, index?)?) → bool

True when fn is true for any item (or, without fn, if the list isn't empty).

->any(fn(item, index?)?) is true when the function is true for at least one item. It stops at the first item that passes. Without a function it asks whether the list has any items at all:

<let name="basket" value="['apple', 'pear', 'fig']" />
<echo value="$basket->any(fn(fruit) => $fruit->starts_with('p'))" /> <!-- true because pear starts with p -->
<echo value="$basket->any(fn(fruit) => $fruit == 'kiwi')" /> <!-- false because no fruit is kiwi -->
<echo value="$basket->any()" /> <!-- true because the basket isn't empty -->
$basket = ['apple', 'pear', 'fig']
echo $basket->any(fn(fruit) => $fruit->starts_with('p'))  // true because pear starts with p
echo $basket->any(fn(fruit) => $fruit == 'kiwi')          // false because no fruit is kiwi
echo $basket->any()                                       // true because the basket isn't empty
ParameterTakes
fn optionalfn
Example
<echo>{ [3, 8, 1]->any(fn(n) => $n > 5) }</echo>
echo [3, 8, 1]->any(fn(n) => $n > 5)

#list->at(index: number) → any

The item at an index; negative counts from the end.

->at(index) gives the item at a position, counting from 0. A negative index counts back from the end, so -1 is the last item. An index past either end gives null rather than an error. $list[index] reads the same item:

<let name="week" value="['mon', 'tue', 'wed']" />
<echo value="$week->at(0)" /> <!-- 'mon' because positions start at 0 -->
<echo value="$week->at(-1)" /> <!-- 'wed' because -1 is the last item -->
<echo value="$week->at(5)" /> <!-- null because there is no sixth item -->
$week = ['mon', 'tue', 'wed']
echo $week->at(0)    // 'mon' because positions start at 0
echo $week->at(-1)   // 'wed' because -1 is the last item
echo $week->at(5)    // null because there is no sixth item
ParameterTakes
index requirednumber
Example
<echo>{ ['a', 'b', 'c']->at(-1) }</echo>
echo ['a', 'b', 'c']->at(-1)

#list->average(fn(item)?) → number

The mean of the items (or of fn for each item), or null when empty.

->average(fn(item)?) adds the items up and divides by how many there are. Given a function, it averages what the function gives for each item. An empty list gives null, since there is nothing to average:

<echo value="[4, 8, 9]->average()" /> <!-- 7 because 4 + 8 + 9 is 21, and 21 / 3 is 7 -->
<let name="orders" value="[{ total: 10 }, { total: 30 }]" />
<echo value="$orders->average(.total)" /> <!-- 20 because 10 + 30 is 40, and 40 / 2 is 20 -->
<echo value="[]->average()" /> <!-- null because there is nothing to average -->
echo [4, 8, 9]->average()     // 7 because 4 + 8 + 9 is 21, and 21 / 3 is 7
$orders = [{ total: 10 }, { total: 30 }]
echo $orders->average(.total) // 20 because 10 + 30 is 40, and 40 / 2 is 20
echo []->average()            // null because there is nothing to average
ParameterTakes
fn optionalfn
Example
<echo>{ [4, 8, 9]->average() }</echo>
echo [4, 8, 9]->average()

#list->cells(row?: number, rows?: bool, column?: number, columns?: bool) → any

The cells of a list of lists, such as a ->grid(). On its own, or with rows, every row; with columns, every column, top to bottom. row: picks one row and column: one column, each counted from 0 (-1 is the last). A row and a column together give the one cell where they meet. Rows may be different lengths: a column skips the rows too short to reach it. 'ab\ncd'->grid()->cells(columns) is [['a', 'c'], ['b', 'd']].

->cells(rows?, columns?, row:?, column:?) reads a list of lists, such as a ->grid(), like a table. On its own, or with rows, it gives every row; with columns it gives every column, top to bottom. row: picks one row and column: one column, each counted from 0 with -1 for the last, and the two together give the one cell where they meet. Rows may be different lengths: a column skips the rows too short to reach it.

<let name="garden">```text
    #.#
    ..#
    ```</let>

<let name="plot" value="$garden->grid()" />
<echo value="$plot->cells(rows)" /> <!-- [['#', '.', '#'], ['.', '.', '#']] because each line is a row -->
<echo value="$plot->cells(columns)" /> <!-- [['#', '.'], ['.', '.'], ['#', '#']] because each column takes one character from every line -->

<for each="column" in="$plot->cells(columns)">
  <echo value="$column->join('')" />
</for>
<!-- '#.' then '..' then '##' because the loop goes through the columns left to right -->

<echo value="$plot->cells(row: 0)" /> <!-- ['#', '.', '#'] because row 0 is the top line -->
<echo value="$plot->cells(column: -1)" /> <!-- ['#', '#'] because -1 is the last column -->
<echo value="$plot->cells(row: 1, column: 2)" /> <!-- '#' because row 1 is '..#' and column 2 is its last character -->
<echo value="[[1, 2], [3, 4]]->cells(columns)" /> <!-- [[1, 3], [2, 4]] because any list of lists has columns too -->
$garden = ```text
#.#
..#
```

$plot = $garden->grid()
echo $plot->cells(rows)               // [['#', '.', '#'], ['.', '.', '#']] because each line is a row
echo $plot->cells(columns)            // [['#', '.'], ['.', '.'], ['#', '#']] because each column takes one character from every line

for column in $plot->cells(columns) {
  echo $column->join('')
}
// '#.' then '..' then '##' because the loop goes through the columns left to right

echo $plot->cells(row: 0)             // ['#', '.', '#'] because row 0 is the top line
echo $plot->cells(column: -1)         // ['#', '#'] because -1 is the last column
echo $plot->cells(row: 1, column: 2)  // '#' because row 1 is '..#' and column 2 is its last character
echo [[1, 2], [3, 4]]->cells(columns) // [[1, 3], [2, 4]] because any list of lists has columns too
ParameterTakes
row optionalnumber
rows optionala flag: rows or not rows
column optionalnumber
columns optionala flag: columns or not columns

Arguments can be named: ->cells(…, rows: …, column: …).

Example
<echo>{ [[1, 2, 3], [4, 5, 6]]->cells(columns) }</echo>
echo [[1, 2, 3], [4, 5, 6]]->cells(columns)

#list->chunk(size: number) → list

The items in lists of size.

->chunk(size) cuts the list into lists of size items, in order. The last list holds whatever is left, so it can be shorter:

<let name="seats" value="['ada', 'bo', 'cy', 'di', 'ed']" />
<echo value="$seats->chunk(2)" /> <!-- [['ada', 'bo'], ['cy', 'di'], ['ed']] because 5 people fill two tables of 2 and leave 1 -->
$seats = ['ada', 'bo', 'cy', 'di', 'ed']
echo $seats->chunk(2)   // [['ada', 'bo'], ['cy', 'di'], ['ed']] because 5 people fill two tables of 2 and leave 1
ParameterTakes
size requirednumber
Example
<echo>{ [1, 2, 3, 4, 5]->chunk(2) }</echo>
echo [1, 2, 3, 4, 5]->chunk(2)

#list->combinations(size: number) → list

Every way to pick size items, order not mattering, in list order: [1, 2, 3]->combinations(2) is [[1, 2], [1, 3], [2, 3]].

->combinations(size) gives every way to pick size items when the order of the picked items doesn't matter. Each pick keeps the items in list order, and no item is picked twice in the same pick.

Picking 2 from ['tea', 'milk', 'juice'] works like this: pair tea with each item after it (milk, then juice), then pair milk with each item after it (juice). juice has nothing after it, so that's all. ['milk', 'tea'] never appears, because it is the same pick as ['tea', 'milk']:

<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->combinations(2)" /> <!-- [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2 -->
<echo value="$drinks->combinations(3)" /> <!-- [['tea', 'milk', 'juice']] because there is only one way to pick all 3 -->
<echo value="$drinks->combinations(4)" /> <!-- [] because you can't pick 4 from 3 -->
$drinks = ['tea', 'milk', 'juice']
echo $drinks->combinations(2)   // [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2
echo $drinks->combinations(3)   // [['tea', 'milk', 'juice']] because there is only one way to pick all 3
echo $drinks->combinations(4)   // [] because you can't pick 4 from 3

A common use is checking every pair, such as finding the two prices that add up to a total:

<let name="prices" value="[15, 40, 25, 60]" />
<let name="pair" value="$prices->combinations(2)->find(fn(two) => $two->sum() == 65)" />
<echo value="$pair" /> <!-- [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is -->
$prices = [15, 40, 25, 60]
$pair = $prices->combinations(2)->find(fn(two) => $two->sum() == 65)
echo $pair   // [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is

The number of picks grows fast, so past a million lists it stops with a Limit error rather than run out of memory.

A function with one parameter per picked item gets them one by one, at any size: $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70) gets each pair as cheaper and dearer, and ->combinations(3) fills fn(first, second, third). It then doesn't get the index.

ParameterTakes
size requirednumber
Example
<echo>{ [1, 2, 3]->combinations(2) }</echo>
echo [1, 2, 3]->combinations(2)

#list->common(count?: number, least?: bool, by?: fn(item)) → list

The items that occur most often, most first, each once and as they are (numbers stay numbers): [3, 7, 7, 9, 9, 9]->common(2) is [9, 7]. With least, the rarest come first instead: ->common(1, least) is [3]. Ties keep list order. Without count, every distinct item. Items match with ==, or by what by: gives for each.

->common(count?, least, by?) counts how often each item occurs and gives the items back in that order, each once. Without least the most common come first; with least the rarest do. count keeps that many from the front, and without it you get every distinct item. Items that occur equally often stay in the order they first appear, and each comes back as it is, so numbers stay numbers:

<let name="basket" value="['apple', 'pear', 'apple', 'fig', 'fig', 'apple']" />
<!-- apple occurs 3 times, fig twice and pear once. -->
<echo value="$basket->common()" /> <!-- ['apple', 'fig', 'pear'] because that is most to least -->
<echo value="$basket->common(1)" /> <!-- ['apple'] because it is the 1st most common -->
<echo value="$basket->common(1, least)" /> <!-- ['pear'] because it is the 1st least common -->
<echo value="$basket->common(least)" /> <!-- ['pear', 'fig', 'apple'] because that is least to most -->
$basket = ['apple', 'pear', 'apple', 'fig', 'fig', 'apple']
// apple occurs 3 times, fig twice and pear once.
echo $basket->common()           // ['apple', 'fig', 'pear'] because that is most to least
echo $basket->common(1)          // ['apple'] because it is the 1st most common
echo $basket->common(1, least)   // ['pear'] because it is the 1st least common
echo $basket->common(least)      // ['pear', 'fig', 'apple'] because that is least to most

by: decides what counts as the same item. The item you get back is the first one of its kind:

<let name="drinks" value="['Tea', 'milk', 'tea']" />
<echo value="$drinks->common(1, by: fn(drink) => $drink->lower())" /> <!-- ['Tea'] because 'Tea' and 'tea' count as one drink, twice -->
$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower())   // ['Tea'] because 'Tea' and 'tea' count as one drink, twice
ParameterTakes
count optionalnumber
least optionala flag: least or not least
by optionalfn

Arguments can be named: ->common(…, least: …, by: …).

Example
<echo>{ [3, 7, 7, 9, 9, 9]->common(2) }</echo>
echo [3, 7, 7, 9, 9, 9]->common(2)

#list->contains(item) → bool

True when the list contains the item.

->contains(item) is true when the list has an item equal to the one given. It compares with ==, so the number 1 and the text '1' match:

<let name="guests" value="['ada', 'bo']" />
<echo value="$guests->contains('bo')" /> <!-- true -->
<echo value="$guests->contains('cy')" /> <!-- false -->
<echo value="[1, 2, 3]->contains('2')" /> <!-- true because == finds '2' equal to 2 -->
$guests = ['ada', 'bo']
echo $guests->contains('bo')     // true
echo $guests->contains('cy')     // false
echo [1, 2, 3]->contains('2')    // true because == finds '2' equal to 2

To ask whether any item passes a test rather than equals a value, use ->any().

Example
<echo>{ ['tea', 'coffee']->contains('tea') }</echo>
echo ['tea', 'coffee']->contains('tea')

#list->count() → number

The number of items.

->count() gives how many items the list has:

<echo value="['tea', 'milk', 'juice']->count()" /> <!-- 3 -->
<echo value="[]->count()" /> <!-- 0 -->
echo ['tea', 'milk', 'juice']->count()   // 3
echo []->count()                         // 0
Example
<echo>{ ['a', 'b', 'c']->count() }</echo>
echo ['a', 'b', 'c']->count()

#list->count_by(fn(item)) → map

A map from fn's result to how many items gave it: ['a', 'bb', 'cc']->count_by(->count()) is { 1: 1, 2: 2 }.

->count_by(fn(item)) groups the items by what the function gives for each, and counts each group. The result is a map from each answer to its count:

<let name="words" value="['apple', 'avocado', 'banana']" />
<echo value="$words->count_by(fn(word) => $word->first())" /> <!-- { a: 2, b: 1 } because two words start with a and one with b -->
$words = ['apple', 'avocado', 'banana']
echo $words->count_by(fn(word) => $word->first())   // { a: 2, b: 1 } because two words start with a and one with b
ParameterTakes
fn requiredfn
Example
<echo>{ ['apple', 'avocado', 'banana']->count_by(fn(f) => $f->first()) }</echo>
echo ['apple', 'avocado', 'banana']->count_by(fn(f) => $f->first())

#list->count_of(match) → number

Counts items for which a function is true, or items equal to a value using ==.

->count_of(match) counts the items equal to a value (with ==), or, given a function, the items for which it is true:

<let name="rolls" value="[6, 2, 6, 5, 6]" />
<echo value="$rolls->count_of(6)" /> <!-- 3 because three rolls are 6 -->
<echo value="$rolls->count_of(fn(roll) => $roll > 4)" /> <!-- 4 because 6, 6, 5 and 6 are above 4 -->
$rolls = [6, 2, 6, 5, 6]
echo $rolls->count_of(6)                      // 3 because three rolls are 6
echo $rolls->count_of(fn(roll) => $roll > 4)  // 4 because 6, 6, 5 and 6 are above 4
Example
<echo>{ [1, 2, 3, 4]->count_of(fn(n) => $n > 2) }</echo>
echo [1, 2, 3, 4]->count_of(fn(n) => $n > 2)

#list->difference(other: list, by?: fn(item)) → list

The items that aren't in other, each once and in order. Items match with ==, or by what by: gives for each.

->difference(other, by?) gives the items that aren't in the other list, each once and in this list's order. Items match with ==, or by what by: gives for each:

<let name="invited" value="['ada', 'bo', 'cy', 'di']" />
<let name="replied" value="['bo', 'di']" />
<echo value="$invited->difference($replied)" /> <!-- ['ada', 'cy'] because bo and di have replied -->
$invited = ['ada', 'bo', 'cy', 'di']
$replied = ['bo', 'di']
echo $invited->difference($replied)   // ['ada', 'cy'] because bo and di have replied
ParameterTakes
other requiredlist
by optionalfn

Arguments can be named: ->difference(…, by: …).

Example
<echo>{ [1, 2, 3, 4]->difference([2, 4]) }</echo>
echo [1, 2, 3, 4]->difference([2, 4])

#list->each(fn(item, index?)) → list

Calls fn for each item and returns the list.

->each(fn(item, index?)) calls the function for each item, for what it does rather than what it gives back, and returns the list unchanged so you can keep chaining. A function written with => holds one expression, so ->each() suits a call that does something, such as logging or saving each item:

<let name="tasks" value="['wash', 'dry', 'fold']" />
<let name="same" value="$tasks->each(fn(task) => $log->info(&quot;Doing { $task }&quot;))" />
<!-- logs Doing wash, Doing dry and Doing fold -->
<echo value="$same" /> <!-- ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on -->
$tasks = ['wash', 'dry', 'fold']
$same = $tasks->each(fn(task) => $log->info("Doing { $task }"))
// logs Doing wash, Doing dry and Doing fold
echo $same   // ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on

To run statements for each item, such as echo, write a for loop: for task at index in $tasks { echo "{ $index + 1 }. { $task }" }.

ParameterTakes
fn requiredfn
Example
<do>['a', 'b']->each(fn(x) => $x->upper())</do>
<echo>each runs fn for every item and returns the list.</echo>
['a', 'b']->each(fn(x) => $x->upper())
echo 'each runs fn for every item and returns the list.'

#list->filter(fn(item, index?)) → list

The items for which fn(item, index) is true.

->filter(fn(item, index?)) keeps the items for which the function is true, in order:

<let name="scores" value="[72, 45, 91, 38]" />
<echo value="$scores->filter(fn(score) => $score >= 50)" /> <!-- [72, 91] because 45 and 38 are below 50 -->

<let name="people" value="[{ name: 'Ada', active: true }, { name: 'Bo', active: false }]" />
<echo value="$people->filter(.active)->pluck(name)" /> <!-- ['Ada'] because only Ada is active -->
$scores = [72, 45, 91, 38]
echo $scores->filter(fn(score) => $score >= 50)   // [72, 91] because 45 and 38 are below 50

$people = [{ name: 'Ada', active: true }, { name: 'Bo', active: false }]
echo $people->filter(.active)->pluck(name)        // ['Ada'] because only Ada is active

->reject() keeps the others.

ParameterTakes
fn requiredfn
Example
<echo>{ [1, 2, 3, 4, 5]->filter(fn(n) => $n % 2 == 1) }</echo>
echo [1, 2, 3, 4, 5]->filter(fn(n) => $n % 2 == 1)

#list->find(fn(item, index?), last?: bool) → any

The first item for which fn(item, index) is true, or with last, the last one; null when none is.

->find(fn(item, index?), last?) gives the first item for which the function is true, or with last, the last one. It gives null when no item passes:

<let name="rolls" value="[2, 6, 3, 6, 1]" />
<echo value="$rolls->find(fn(roll) => $roll > 4)" /> <!-- 6 because 6 is the first roll above 4 -->
<echo value="$rolls->find(fn(roll) => $roll &lt; 3, last)" /> <!-- 1 because 1 is the last roll below 3 -->
<echo value="$rolls->find(fn(roll) => $roll > 6)" /> <!-- null because no roll is above 6 -->
$rolls = [2, 6, 3, 6, 1]
echo $rolls->find(fn(roll) => $roll > 4)         // 6 because 6 is the first roll above 4
echo $rolls->find(fn(roll) => $roll < 3, last)   // 1 because 1 is the last roll below 3
echo $rolls->find(fn(roll) => $roll > 6)         // null because no roll is above 6
ParameterTakes
fn requiredfn
last optionala flag: last or not last

Arguments can be named: ->find(…, last: …).

Example
<echo>{ [{ id: 1, name: 'Joan' }, { id: 2, name: 'Sam' }]->find(fn(p) => $p.id == 2).name }</echo>
echo [{ id: 1, name: 'Joan' }, { id: 2, name: 'Sam' }]->find(fn(p) => $p.id == 2).name

#list->first() → any

The first item, or null.

->first() gives the first item, or null for an empty list:

<echo value="['gold', 'silver', 'bronze']->first()" /> <!-- 'gold' -->
<echo value="[]->first()" /> <!-- null because there is no first item -->
echo ['gold', 'silver', 'bronze']->first()   // 'gold'
echo []->first()                             // null because there is no first item
Example
<echo>{ ['tea', 'coffee']->first() }</echo>
echo ['tea', 'coffee']->first()

#list->flat_map(fn(item, index?)) → list

Maps each item, then spreads each result list by one level.

->flat_map(fn(item, index?)) is ->map() for a function that gives a list: each item's list is spread into one flat list, rather than kept as a list of lists:

<let name="lines" value="['tea milk', 'juice']" />
<echo value="$lines->map(fn(line) => $line->words())" /> <!-- [['tea', 'milk'], ['juice']] because ->map() keeps each list -->
<echo value="$lines->flat_map(fn(line) => $line->words())" /> <!-- ['tea', 'milk', 'juice'] because ->flat_map() spreads them -->
$lines = ['tea milk', 'juice']
echo $lines->map(fn(line) => $line->words())        // [['tea', 'milk'], ['juice']] because ->map() keeps each list
echo $lines->flat_map(fn(line) => $line->words())   // ['tea', 'milk', 'juice'] because ->flat_map() spreads them
ParameterTakes
fn requiredfn
Example
<echo>{ [1, 2]->flat_map(fn(n) => [$n, -$n]) }</echo>
echo [1, 2]->flat_map(fn(n) => [$n, -$n])

#list->flatten() → list

Lists inside the list are spread into it.

->flatten() spreads the lists inside a list into it, one level deep. A list inside a list inside a list keeps its inner list:

<echo value="[['tea', 'milk'], ['juice']]->flatten()" /> <!-- ['tea', 'milk', 'juice'] -->
<echo value="[[1, [2]], 3]->flatten()" /> <!-- [1, [2], 3] because only one level is spread -->
echo [['tea', 'milk'], ['juice']]->flatten()   // ['tea', 'milk', 'juice']
echo [[1, [2]], 3]->flatten()                  // [1, [2], 3] because only one level is spread
Example
<echo>{ [[1, 2], [3], [4, 5]]->flatten() }</echo>
echo [[1, 2], [3], [4, 5]]->flatten()

#list->group_by(fn(item)) → map

A map from fn's result to the items that gave it.

->group_by(fn(item)) puts the items into groups by what the function gives for each. The result is a map from each answer to the items that gave it, in order:

<let name="words" value="['tea', 'tap', 'milk']" />
<echo value="$words->group_by(fn(word) => $word->first())" /> <!-- { t: ['tea', 'tap'], m: ['milk'] } because tea and tap start with t -->
$words = ['tea', 'tap', 'milk']
echo $words->group_by(fn(word) => $word->first())   // { t: ['tea', 'tap'], m: ['milk'] } because tea and tap start with t

->count_by() gives how many are in each group instead.

ParameterTakes
fn requiredfn
Example
<echo>{ ['apple', 'avocado', 'banana']->group_by(fn(f) => $f->first()) }</echo>
echo ['apple', 'avocado', 'banana']->group_by(fn(f) => $f->first())

#list->index_of(item, last?: bool) → number

The index of an item (compared with ==), or of the first item for which a fn(item, index) is true; with last, the last one. -1 when there is none.

->index_of(item, last?) gives the position of the first item equal to the one given (with ==), or of the first item for which a function is true. With last it looks from the end. It gives -1 when there is none:

<let name="queue" value="['ada', 'bo', 'cy', 'bo']" />
<echo value="$queue->index_of('bo')" /> <!-- 1 because positions start at 0 -->
<echo value="$queue->index_of('bo', last)" /> <!-- 3 because the last bo is 4th -->
<echo value="$queue->index_of(fn(name) => $name->count() > 2)" /> <!-- 0 because ada is the first name longer than 2 -->
<echo value="$queue->index_of('di')" /> <!-- -1 because di isn't in the queue -->
$queue = ['ada', 'bo', 'cy', 'bo']
echo $queue->index_of('bo')                            // 1 because positions start at 0
echo $queue->index_of('bo', last)                      // 3 because the last bo is 4th
echo $queue->index_of(fn(name) => $name->count() > 2)  // 0 because ada is the first name longer than 2
echo $queue->index_of('di')                            // -1 because di isn't in the queue
ParameterTakes
item requiredany value
last optionala flag: last or not last

Arguments can be named: ->index_of(…, last: …).

Example
<echo>{ ['a', 'b', 'c']->index_of('c') }</echo>
echo ['a', 'b', 'c']->index_of('c')

#list->insert(index: number, item) → list

A new list with item inserted at index.

->insert(index, item) gives a new list with the item put in at that position; the items from there on move along one. A negative index counts from the end, so -1 puts the item before the last one:

<let name="week" value="['mon', 'wed']" />
<echo value="$week->insert(1, 'tue')" /> <!-- ['mon', 'tue', 'wed'] because tue goes in at position 1 -->
$week = ['mon', 'wed']
echo $week->insert(1, 'tue')   // ['mon', 'tue', 'wed'] because tue goes in at position 1
ParameterTakes
index requirednumber
item requiredany value

Arguments can be named: ->insert(…, item: …).

Example
<echo>{ ['a', 'c']->insert(1, 'b') }</echo>
echo ['a', 'c']->insert(1, 'b')

#list->intersect(other: list, by?: fn(item)) → list

The items that are in other too, each once and in order. Items match with ==, or by what by: gives for each.

->intersect(other, by?) gives the items that are in the other list too, each once and in this list's order. Items match with ==, or by what by: gives for each:

<let name="mine" value="['tea', 'milk', 'juice']" />
<let name="yours" value="['juice', 'tea', 'cola']" />
<echo value="$mine->intersect($yours)" /> <!-- ['tea', 'juice'] because both lists have tea and juice -->

<let name="people" value="[{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]" />
<echo value="$people->intersect([{ id: 2 }], by: .id)->pluck(name)" /> <!-- ['Bo'] because only Bo's id is in both -->
$mine = ['tea', 'milk', 'juice']
$yours = ['juice', 'tea', 'cola']
echo $mine->intersect($yours)   // ['tea', 'juice'] because both lists have tea and juice

$people = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]
echo $people->intersect([{ id: 2 }], by: .id)->pluck(name)   // ['Bo'] because only Bo's id is in both
ParameterTakes
other requiredlist
by optionalfn

Arguments can be named: ->intersect(…, by: …).

Example
<echo>{ ['tea', 'coffee', 'milk']->intersect(['milk', 'tea']) }</echo>
echo ['tea', 'coffee', 'milk']->intersect(['milk', 'tea'])

#list->is_empty() → bool

True when the list has no items.

->is_empty() is true when the list has no items:

<echo value="[]->is_empty()" /> <!-- true -->
<echo value="['tea']->is_empty()" /> <!-- false -->
echo []->is_empty()          // true
echo ['tea']->is_empty()     // false
Example
<echo>{ []->is_empty() }</echo>
echo []->is_empty()

#list->join(separator?) → string

The items joined into text (', ' by default).

->join(separator?) puts the items together into one text, with the separator between them, ', ' unless you give another:

<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->join()" /> <!-- 'tea, milk, juice' -->
<echo value="$drinks->join(' or ')" /> <!-- 'tea or milk or juice' -->
<echo value="$drinks->join('')" /> <!-- 'teamilkjuice' -->
$drinks = ['tea', 'milk', 'juice']
echo $drinks->join()        // 'tea, milk, juice'
echo $drinks->join(' or ')  // 'tea or milk or juice'
echo $drinks->join('')      // 'teamilkjuice'
Example
<echo>{ ['a', 'b', 'c']->join(' / ') }</echo>
echo ['a', 'b', 'c']->join(' / ')

#list->last() → any

The last item, or null.

->last() gives the last item, or null for an empty list:

<echo value="['gold', 'silver', 'bronze']->last()" /> <!-- 'bronze' -->
<echo value="[]->last()" /> <!-- null -->
echo ['gold', 'silver', 'bronze']->last()   // 'bronze'
echo []->last()                             // null
Example
<echo>{ ['tea', 'coffee']->last() }</echo>
echo ['tea', 'coffee']->last()

#list->map(fn(item, index?)) → list

A new list with fn(item, index) applied to each item.

->map(fn(item, index?)) gives a new list with the function's answer for each item, in the same order:

<let name="prices" value="[2, 5, 10]" />
<echo value="$prices->map(fn(price) => $price * 2)" /> <!-- [4, 10, 20] because each price is doubled -->
<echo value="['tea', 'milk']->map(.upper())" /> <!-- ['TEA', 'MILK'] because .upper() calls ->upper() on each -->
<echo value="['tea', 'milk']->map(fn(drink, index) => &quot;{ $index }:{ $drink }&quot;)" /> <!-- ['0:tea', '1:milk'] -->
$prices = [2, 5, 10]
echo $prices->map(fn(price) => $price * 2)                // [4, 10, 20] because each price is doubled
echo ['tea', 'milk']->map(.upper())                       // ['TEA', 'MILK'] because .upper() calls ->upper() on each
echo ['tea', 'milk']->map(fn(drink, index) => "{ $index }:{ $drink }")   // ['0:tea', '1:milk']
ParameterTakes
fn requiredfn
Example
<echo>{ [1, 2, 3]->map(fn(n) => $n * 10) }</echo>
echo [1, 2, 3]->map(fn(n) => $n * 10)

#list->max(by?: fn(item)) → any

The largest item, or the item with the largest by: fn(item): ->max(by: .score).

->max(by?) gives the largest item, or with by:, the item for which by: gives the largest value. It gives null for an empty list:

<echo value="[72, 91, 45]->max()" /> <!-- 91 -->
<let name="players" value="[{ name: 'Ada', score: 72 }, { name: 'Bo', score: 91 }]" />
<echo value="$players->max(by: .score).name" /> <!-- 'Bo' because Bo has the highest score -->
echo [72, 91, 45]->max()   // 91
$players = [{ name: 'Ada', score: 72 }, { name: 'Bo', score: 91 }]
echo $players->max(by: .score).name   // 'Bo' because Bo has the highest score
ParameterTakes
by optionalfn
Example
<echo>{ [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 35 }]->max(by: .age).name }</echo>
echo [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 35 }]->max(by: .age).name

#list->min(by?: fn(item)) → any

The smallest item, or the item with the smallest by: fn(item): ->min(by: .price).

->min(by?) gives the smallest item, or with by:, the item for which by: gives the smallest value:

<echo value="[72, 91, 45]->min()" /> <!-- 45 -->
<let name="shops" value="[{ name: 'corner', price: 3 }, { name: 'market', price: 2 }]" />
<echo value="$shops->min(by: .price).name" /> <!-- 'market' because it is the cheapest -->
echo [72, 91, 45]->min()   // 45
$shops = [{ name: 'corner', price: 3 }, { name: 'market', price: 2 }]
echo $shops->min(by: .price).name   // 'market' because it is the cheapest
ParameterTakes
by optionalfn
Example
<echo>{ [4, 9, 2]->min() }</echo>
echo [4, 9, 2]->min()

#list->numbers() → number[]

Every number in the list, in order: numbers stay as they are, text gives the numbers in it, and lists inside are read too, so ['-3 4', 5]->numbers() is [-3, 4, 5]. Other items are skipped.

->numbers() gives every number in the list, in order. Numbers stay as they are, text gives the numbers written in it (as text's ->numbers() does), and lists inside are read too. Anything else is skipped:

<echo value="['-3 4', 5]->numbers()" /> <!-- [-3, 4, 5] because the text holds -3 and 4 -->
<echo value="[[1, 2], 'and 3', true]->numbers()" /> <!-- [1, 2, 3] because true isn't a number -->
echo ['-3 4', 5]->numbers()            // [-3, 4, 5] because the text holds -3 and 4
echo [[1, 2], 'and 3', true]->numbers() // [1, 2, 3] because true isn't a number
Example
<echo>{ ['-3 4', 5]->numbers() }</echo>
echo ['-3 4', 5]->numbers()

#list->only(what: word) → list

The items of a type (->only(semver), ->only(number)) or that a filter of the items' type keeps (->only(releases) on a semver[]).

->only(what) keeps the items of one type, written as a bare word: ->only(number), ->only(string). On a list of a native type it also takes that type's own filters, such as ->only(prereleases) on a semver[]:

<let name="mixed" value="[3, 'tea', 7, true]" />
<echo value="$mixed->only(number)" /> <!-- [3, 7] because only 3 and 7 are numbers -->

<let name="versions" type="semver[]" value="['1.2.0', '2.0.0-beta', '1.10.0']" />
<echo value="$versions->only(prereleases)" /> <!-- ['2.0.0-beta'] because only that version has a -beta part -->
$mixed = [3, 'tea', 7, true]
echo $mixed->only(number)   // [3, 7] because only 3 and 7 are numbers

$versions: semver[] = ['1.2.0', '2.0.0-beta', '1.10.0']
echo $versions->only(prereleases)   // ['2.0.0-beta'] because only that version has a -beta part

->without() keeps the others.

ParameterTakes
what requiredword
Example
<let name="loads" value="[1, 'two', 3]" />
<echo>{ $loads->only(number) }</echo>
$loads = [1, 'two', 3]
echo $loads->only(number)

#list->partition(fn(item, index?)) → list

Returns [matching, remaining], testing each item once.

->partition(fn(item, index?)) splits the list in two in one pass: the items for which the function is true, then the rest. It gives both as a list of two lists:

<let name="numbers" value="[1, 2, 3, 4]" />
<echo value="$numbers->partition(fn(number) => $number->is_even())" /> <!-- [[2, 4], [1, 3]] because 2 and 4 are even -->
$numbers = [1, 2, 3, 4]
echo $numbers->partition(fn(number) => $number->is_even())   // [[2, 4], [1, 3]] because 2 and 4 are even
ParameterTakes
fn requiredfn
Example
<echo>{ [1, 2, 3]->partition(fn(n) => $n->is_odd()) }</echo>
echo [1, 2, 3]->partition(fn(n) => $n->is_odd())

#list->permutations(size?: number) → list

Every ordering of size items (all of them by default), in list order: [1, 2, 3]->permutations(2) is [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]].

->permutations(size?) gives every ordering of the items. Unlike ->combinations(), order matters, so ['tea', 'milk'] and ['milk', 'tea'] are both there. Without size each ordering uses every item:

<let name="drinks" value="['tea', 'milk', 'juice']" />
<echo value="$drinks->permutations()->count()" /> <!-- 6 because 3 choices for first, 2 for second and 1 for third -->
<echo value="$drinks->permutations(2)->first()" /> <!-- ['tea', 'milk'] because orderings come in list order -->
<echo value="['tea', 'milk']->permutations()" /> <!-- [['tea', 'milk'], ['milk', 'tea']] -->
$drinks = ['tea', 'milk', 'juice']
echo $drinks->permutations()->count()     // 6 because 3 choices for first, 2 for second and 1 for third
echo $drinks->permutations(2)->first()    // ['tea', 'milk'] because orderings come in list order
echo ['tea', 'milk']->permutations()      // [['tea', 'milk'], ['milk', 'tea']]

Past a million orderings it stops with a Limit error.

ParameterTakes
size optionalnumber
Example
<echo>{ ['a', 'b', 'c']->permutations() }</echo>
echo ['a', 'b', 'c']->permutations()

#list->pluck(key: Self.fields|Self.fields[]) → list

One field from each item, or a map of the selected fields for each item when given a list of keys.

->pluck(key) gives one field from each item, in order. Given a list of keys, it gives a map of just those fields for each item. A missing field gives null:

<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam' }]" />
<echo value="$people->pluck(name)" /> <!-- ['Joan', 'Sam'] -->
<echo value="$people->pluck([name, age])" /> <!-- [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] because Sam has no age -->
$people = [{ name: 'Joan', age: 82 }, { name: 'Sam' }]
echo $people->pluck(name)          // ['Joan', 'Sam']
echo $people->pluck([name, age])   // [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] because Sam has no age
ParameterTakes
key requiredSelf.fields|Self.fields[]
Example
<echo>{ [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 35 }]->pluck([name, age]) }</echo>
echo [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 35 }]->pluck([name, age])

#list->pop() → list

A new list without its last item.

->pop() gives a new list without its last item:

<let name="stack" value="['plate', 'bowl', 'cup']" />
<echo value="$stack->pop()" /> <!-- ['plate', 'bowl'] because cup was on top -->
$stack = ['plate', 'bowl', 'cup']
echo $stack->pop()   // ['plate', 'bowl'] because cup was on top

To read the last item, use ->last().

Example
<echo>{ [1, 2, 3]->pop() }</echo>
echo [1, 2, 3]->pop()

#list->positions_of(item) → list

Where an item is in a list of lists, such as a ->grid(): every cell equal to it (compared with ==), or for which a fn(cell) is true, as a point { row, column }, row by row and left to right. '#.\n.#'->grid()->positions_of('#') is [{ row: 0, column: 0 }, { row: 1, column: 1 }]. Look a point up with ->contains({ row: 1, column: 1 }).

->positions_of(item) gives every place an item is in a list of lists, such as a ->grid(), as points with a .row and a .column, row by row and left to right. Cells match with ==, or when a function given instead is true for them. Look a point up with ->contains({ row: ..., column: ... }):

<let name="garden">```text
    #.#
    ..#
    ```</let>

<let name="trees" value="$garden->grid()->positions_of('#')" />
<echo value="$trees" /> <!-- [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first -->
<echo value="$trees->contains({ row: 1, column: 2 })" /> <!-- true because row 1 ends in # -->
<echo value="$garden->grid()->positions_of(fn(cell) => $cell != '#')->count()" />
<!-- 3 because three cells are not trees -->
$garden = ```text
#.#
..#
```

$trees = $garden->grid()->positions_of('#')
echo $trees                                    // [{ row: 0, column: 0 }, { row: 0, column: 2 }, { row: 1, column: 2 }] because those are the three #s, top line first
echo $trees->contains({ row: 1, column: 2 })   // true because row 1 ends in #
echo $garden->grid()->positions_of(fn(cell) => $cell != '#')->count()
// 3 because three cells are not trees

With ->combinations(2), a function with two parameters gets each pair of points one by one. This counts the squares whose four corners are all trees:

<let name="field">```text
    #.##.
    .....
    .#...
    ##.##
    ```</let>

<let name="trees" value="$field->grid()->positions_of('#')" />
<echo value="$trees->combinations(2)->count_of(fn(left, right) {
    // only two trees on the same row can be a square's top corners
if $left.row != $right.row {
  return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
    $size = $right.column - $left.column
    return $trees->contains({ row: $left.row + $size, column: $left.column })
      and $trees->contains({ row: $left.row + $size, column: $right.column })
  })" />
<!-- 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them -->
$field = ```text
#.##.
.....
.#...
##.##
```

$trees = $field->grid()->positions_of('#')
echo $trees->combinations(2)->count_of(fn(left, right) {
  // only two trees on the same row can be a square's top corners
  if $left.row != $right.row {
    return false
  }
  // the gap between them is the square's width, so the bottom corners sit that many rows down
  $size = $right.column - $left.column
  return $trees->contains({ row: $left.row + $size, column: $left.column })
    and $trees->contains({ row: $left.row + $size, column: $right.column })
})
// 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them
Example
<echo>{ ('#.' + @char_of(10) + '.#')->grid()->positions_of('#') }</echo>
echo ('#.' + @char_of(10) + '.#')->grid()->positions_of('#')

#list->prepend(items...) → list

A new list with items added to the start.

->prepend(items...) gives a new list with the items put at the start, in the order given:

<let name="queue" value="['cy', 'di']" />
<echo value="$queue->prepend('ada', 'bo')" /> <!-- ['ada', 'bo', 'cy', 'di'] -->
$queue = ['cy', 'di']
echo $queue->prepend('ada', 'bo')   // ['ada', 'bo', 'cy', 'di']
Example
<echo>{ [2, 3]->prepend(1) }</echo>
echo [2, 3]->prepend(1)

#list->product(fn(item)?) → number

The items multiplied together (or fn for each item); 1 for an empty list: [2, 3, 4]->product() is 24.

->product(fn(item)?) multiplies the items together, as ->sum() adds them. Given a function, it multiplies what the function gives for each. An empty list gives 1. Whole numbers stay exact at any size:

<echo value="[2, 3, 4]->product()" /> <!-- 24 because 2 * 3 * 4 is 24 -->
<let name="boxes" value="[{ width: 2 }, { width: 3 }]" />
<echo value="$boxes->product(.width)" /> <!-- 6 because 2 * 3 is 6 -->
<echo value="[]->product()" /> <!-- 1 because multiplying by nothing leaves 1 -->
echo [2, 3, 4]->product()   // 24 because 2 * 3 * 4 is 24
$boxes = [{ width: 2 }, { width: 3 }]
echo $boxes->product(.width)   // 6 because 2 * 3 is 6
echo []->product()          // 1 because multiplying by nothing leaves 1
ParameterTakes
fn optionalfn
Example
<echo>{ [2, 3, 4]->product() }</echo>
echo [2, 3, 4]->product()

#list->push(items...) → list

A new list with items added to the end.

->push(items...) gives a new list with the items added at the end, in the order given:

<let name="drinks" value="['tea']" />
<echo value="$drinks->push('milk', 'juice')" /> <!-- ['tea', 'milk', 'juice'] -->
$drinks = ['tea']
echo $drinks->push('milk', 'juice')   // ['tea', 'milk', 'juice']
Example
<echo>{ [1, 2]->push(3, 4) }</echo>
echo [1, 2]->push(3, 4)

#list->reduce(fn(total, item), initial?) → any

Combines the items into one value: fn(total, item) gives the next total from the last one and the next item, starting from initial: [1, 2, 3]->reduce(fn(total, n) => $total + $n, 10) is 16. Without initial, the first item is the first total, as ->scan() does; an empty list then gives null.

->reduce(fn(total, item), initial?) works through the list to make one value. The function gets the total so far and the next item, and gives the new total. With initial, that is the first total; without it, the first item is:

<let name="basket" value="[3, 5, 2]" />
<echo value="$basket->reduce(fn(total, price) => $total + $price)" /> <!-- 10 because 3, then 3 + 5, then 8 + 2 -->
<echo value="$basket->reduce(fn(total, price) => $total + $price, 100)" /> <!-- 110 because it starts from 100 -->
<echo value="$basket->reduce(fn(biggest, price) => $price > $biggest ? $price : $biggest)" /> <!-- 5 -->
$basket = [3, 5, 2]
echo $basket->reduce(fn(total, price) => $total + $price)       // 10 because 3, then 3 + 5, then 8 + 2
echo $basket->reduce(fn(total, price) => $total + $price, 100)  // 110 because it starts from 100
echo $basket->reduce(fn(biggest, price) => $price > $biggest ? $price : $biggest)   // 5

An empty list gives initial, or null without it. ->scan() keeps every total along the way.

ParameterTakes
fn requiredfn
initial optionalany value

Arguments can be named: ->reduce(…, initial: …).

Example
<echo>{ [1, 2, 3, 4]->reduce(fn(total, n) => $total + $n, 0) }</echo>
echo [1, 2, 3, 4]->reduce(fn(total, n) => $total + $n, 0)

#list->reject(fn(item, index?)) → list

The items for which fn is false.

->reject(fn(item, index?)) keeps the items for which the function is false: the opposite of ->filter():

<let name="scores" value="[72, 45, 91, 38]" />
<echo value="$scores->reject(fn(score) => $score >= 50)" /> <!-- [45, 38] because those are the ones that aren't 50 or more -->
$scores = [72, 45, 91, 38]
echo $scores->reject(fn(score) => $score >= 50)   // [45, 38] because those are the ones that aren't 50 or more
ParameterTakes
fn requiredfn
Example
<echo>{ [1, 2, 3, 4, 5]->reject(fn(n) => $n % 2 == 1) }</echo>
echo [1, 2, 3, 4, 5]->reject(fn(n) => $n % 2 == 1)

#list->remove(item) → list

A new list without any items equal to item.

->remove(item) gives a new list without any items equal to the one given (with ==):

<echo value="['tea', 'milk', 'tea']->remove('tea')" /> <!-- ['milk'] because every tea goes -->
echo ['tea', 'milk', 'tea']->remove('tea')   // ['milk'] because every tea goes
Example
<echo>{ ['a', 'b', 'c']->remove('b') }</echo>
echo ['a', 'b', 'c']->remove('b')

#list->remove_at(index: number) → list

A new list without the item at index.

->remove_at(index) gives a new list without the item at that position. A negative index counts from the end:

<let name="week" value="['mon', 'tue', 'wed']" />
<echo value="$week->remove_at(0)" /> <!-- ['tue', 'wed'] -->
<echo value="$week->remove_at(-1)" /> <!-- ['mon', 'tue'] because -1 is the last item -->
$week = ['mon', 'tue', 'wed']
echo $week->remove_at(0)    // ['tue', 'wed']
echo $week->remove_at(-1)   // ['mon', 'tue'] because -1 is the last item
ParameterTakes
index requirednumber
Example
<echo>{ ['a', 'b', 'c']->remove_at(0) }</echo>
echo ['a', 'b', 'c']->remove_at(0)

#list->replace_at(index: number, item) → list

A new list with the item at index replaced; negative counts from the end.

->replace_at(index, item) gives a new list with the item at that position replaced. A negative index counts from the end, and an index past the end is an Argument error:

<let name="order" value="['tea', 'tae', 'milk']" />
<echo value="$order->replace_at(1, 'juice')" /> <!-- ['tea', 'juice', 'milk'] because position 1 is replaced -->
$order = ['tea', 'tae', 'milk']
echo $order->replace_at(1, 'juice')   // ['tea', 'juice', 'milk'] because position 1 is replaced
ParameterTakes
index requirednumber
item requiredany value

Arguments can be named: ->replace_at(…, item: …).

Example
<echo>{ ['a', 'x', 'c']->replace_at(1, 'b') }</echo>
echo ['a', 'x', 'c']->replace_at(1, 'b')

#list->reverse() → list

A reversed copy.

->reverse() gives a new list with the items in the opposite order:

<echo value="['gold', 'silver', 'bronze']->reverse()" /> <!-- ['bronze', 'silver', 'gold'] -->
echo ['gold', 'silver', 'bronze']->reverse()   // ['bronze', 'silver', 'gold']
Example
<echo>{ [1, 2, 3]->reverse() }</echo>
echo [1, 2, 3]->reverse()

#list->rotate(by: number) → list

The items moved by places, wrapping round: [1, 2, 3, 4]->rotate(1) is [2, 3, 4, 1], and a negative by moves them the other way, [1, 2, 3, 4]->rotate(-1) is [4, 1, 2, 3].

->rotate(by) moves every item by places towards the start, and the items that fall off the front go on the end. A negative by turns the other way:

<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->rotate(1)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end -->
<echo value="$week->rotate(-1)" /> <!-- ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front -->
<echo value="$week->rotate(5)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because 5 places round 4 items is 1 place -->
$week = ['mon', 'tue', 'wed', 'thu']
echo $week->rotate(1)    // ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end
echo $week->rotate(-1)   // ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front
echo $week->rotate(5)    // ['tue', 'wed', 'thu', 'mon'] because 5 places round 4 items is 1 place
ParameterTakes
by requirednumber
Example
<echo>{ [1, 2, 3, 4]->rotate(1) }</echo>
echo [1, 2, 3, 4]->rotate(1)

#list->scan(fn(total, item), initial?) → list

Like ->reduce(), but keeps every running total: [1, 2, 3]->scan(fn(total, n) => $total + $n) is [1, 3, 6]. Without initial, the first item starts the total.

->scan(fn(total, item), initial?) works like ->reduce() but keeps every total along the way, so you can see how the result builds up:

<let name="spending" value="[5, 2, 8, 1]" />
<echo value="$spending->scan(fn(total, amount) => $total + $amount)" /> <!-- [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1 -->
<echo value="$spending->scan(fn(total, amount) => $total - $amount, 20)" /> <!-- [15, 13, 5, 4] because a budget of 20 goes down by each amount -->
$spending = [5, 2, 8, 1]
echo $spending->scan(fn(total, amount) => $total + $amount)       // [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1
echo $spending->scan(fn(total, amount) => $total - $amount, 20)   // [15, 13, 5, 4] because a budget of 20 goes down by each amount
ParameterTakes
fn requiredfn
initial optionalany value

Arguments can be named: ->scan(…, initial: …).

Example
<echo>{ [1, 2, 3, 4]->scan(fn(total, n) => $total + $n) }</echo>
echo [1, 2, 3, 4]->scan(fn(total, n) => $total + $n)

#list->shapes(mask?: any, square?: bool, rectangle?: bool, line?: bool, circle?: bool, of?: any, rotated?: bool, size?: number, radius?: number, distance?: straight|steps|moves) → list

Every place a mask fits (->shapes(Tree), or ->shapes([Block, Ell]) for several), and every square, rectangle, line or circle (name one or several: ->shapes(square, circle, of: '#')) made by the cells that hold of: (a value, or a regex). It looks through text (each line a row, each character a cell, a blank line between layers), a list of values (one row), a grid ($grid[row][column]) or a 3D list ($cube[layer][row][column]); the built-in shapes also take a list of points { row, column }. A mask is a type that extends Mask: its layout is a picture, one character a cell, and each character matches a cell holding the same character, unless its symbols say otherwise (a value, a regex, a fn(cell), or any for a cell that isn't part of the shape). Each match is { kind, points }: kind is the mask's name or the shape, and each point is { row, column, value } (with symbol for a mask, and layer in 3D). With rotated, a mask is tried turned every way the input allows (back to front in a row, the four quarter turns in a grid, all 24 ways round in 3D), and squares, rectangles and lines may lean. A line needs size:, and a circle radius: and distance: straight (the default), steps or moves.

->shapes(mask?, square?, rectangle?, line?, circle?, of?, rotated?, size?, radius?, distance?) finds shapes in text, a list, a grid or a 3D list, and the built-in ones in a list of points { row, column } too. Text is read one row a line and one cell a character, so ->grid() isn't needed first. A mask goes first, by name: a type that extends Mask, whose layout pictures the shape (or a list of them, [Block, Ell]). Every character of the layout matches itself, and symbols says what any other one matches, with any for a cell that isn't part of the shape. For the built-in shapes, name one or several, and say which cells make them with of: (a value or a regex). Each match comes back once as { kind, points }: a square is a square, not also a rectangle. rotated turns a mask every way the input allows and lets the built-in shapes lean, a line needs size:, and a circle needs radius: and, optionally, distance: straight|steps|moves. Mask is also a type for parameters: fn count_in(input: string, shape: Mask) takes any mask.

<let name="plot">```text
    @@@.
    @..@
    @@@@
    ```</let>

<echo value="$plot->shapes(square, of: '@')->count()" /> <!-- 1 because columns 0 and 2 of rows 0 and 2 are all @ -->
<echo value="$plot->shapes(square, rectangle, of: '@')->map(.kind)" /> <!-- ['square', 'rectangle', 'rectangle', 'rectangle'] because each match is counted once -->
<echo value="$plot->shapes(line, of: '@', size: 4)->first().points->map(.column)" />
<!-- [0, 1, 2, 3] because the bottom row is the only 4 @s in a row -->

<type name="Corner" extends="Mask">
  <field name="layout" default="```text
      @@
      @.
      ```" />
  <field name="symbols" default="{ '.': any }" />
</type>

<echo value="$plot->shapes(Corner, rotated)->count()" /> <!-- 3 because the L of three @s fits at three corners of the plot -->
$plot = ```text
@@@.
@..@
@@@@
```

echo $plot->shapes(square, of: '@')->count()                    // 1 because columns 0 and 2 of rows 0 and 2 are all @
echo $plot->shapes(square, rectangle, of: '@')->map(.kind)      // ['square', 'rectangle', 'rectangle', 'rectangle'] because each match is counted once
echo $plot->shapes(line, of: '@', size: 4)->first().points->map(.column)
// [0, 1, 2, 3] because the bottom row is the only 4 @s in a row

type Corner extends Mask {
  layout: ```text
    @@
    @.
    ```
  symbols: { '.': any }
}

echo $plot->shapes(Corner, rotated)->count()             // 3 because the L of three @s fits at three corners of the plot
ParameterTakes
mask optionalany
square optionala flag: square or not square
rectangle optionala flag: rectangle or not rectangle
line optionala flag: line or not line
circle optionala flag: circle or not circle
of optionalany
rotated optionala flag: rotated or not rotated
size optionalnumber
radius optionalnumber
distance optionalone of these words: straight|steps|moves

Arguments can be named: ->shapes(…, square: …, rectangle: …).

Example
<echo>{ [['#', '#'], ['#', '#']]->shapes(square, of: '#')->count() }</echo>
echo [['#', '#'], ['#', '#']]->shapes(square, of: '#')->count()

#list->skip(count: number) → list

All but the first count items.

->skip(count) gives every item after the first count:

<echo value="['header', 'tea', 'milk']->skip(1)" /> <!-- ['tea', 'milk'] because the header line is skipped -->
echo ['header', 'tea', 'milk']->skip(1)   // ['tea', 'milk'] because the header line is skipped
ParameterTakes
count requirednumber
Example
<echo>{ [1, 2, 3, 4]->skip(2) }</echo>
echo [1, 2, 3, 4]->skip(2)

#list->skip_while(fn(item, index?)) → list

The items after those at the start for which fn(item, index) is true.

->skip_while(fn(item, index?)) skips items from the start for as long as the function is true, then keeps everything from the first item that fails, whatever comes after:

<let name="lines" value="['', '', 'tea', '', 'milk']" />
<echo value="$lines->skip_while(.is_empty())" /> <!-- ['tea', '', 'milk'] because only the blank lines at the start go -->
$lines = ['', '', 'tea', '', 'milk']
echo $lines->skip_while(.is_empty())   // ['tea', '', 'milk'] because only the blank lines at the start go
ParameterTakes
fn requiredfn
Example
<echo>{ [2, 4, 5, 6]->skip_while(fn(n) => $n->is_even()) }</echo>
echo [2, 4, 5, 6]->skip_while(fn(n) => $n->is_even())

#list->slice(start: number, end?: number) → list

The items from start up to (not including) end; negative positions count from the end.

->slice(start, end?) gives the items from position start up to, but not including, position end, or to the end of the list. Negative positions count from the end:

<let name="letters" value="['a', 'b', 'c', 'd', 'e']" />
<echo value="$letters->slice(1, 3)" /> <!-- ['b', 'c'] because it stops before position 3 -->
<echo value="$letters->slice(-2)" /> <!-- ['d', 'e'] because -2 is the second to last -->
$letters = ['a', 'b', 'c', 'd', 'e']
echo $letters->slice(1, 3)   // ['b', 'c'] because it stops before position 3
echo $letters->slice(-2)     // ['d', 'e'] because -2 is the second to last
ParameterTakes
start requirednumber
end optionalnumber

Arguments can be named: ->slice(…, end: …).

Example
<echo>{ ['a', 'b', 'c', 'd']->slice(1, 3) }</echo>
echo ['a', 'b', 'c', 'd']->slice(1, 3)

#list->sort(compare?: fn(a, b), by?: fn(item), order?: asc|desc) → list

A sorted copy: by: fn(item) gives the key to sort on, ->sort(by: .name), and order: desc puts the largest first. A compare fn(a, b) gives negative, 0 or positive instead.

->sort(compare?, by?, order?) gives a new list in order, smallest first. Text sorts alphabetically, ignoring case. by: gives what to sort each item on, order: desc puts the largest first, and compare: takes a function of two items that gives a negative number when the first should come first:

<echo value="[3, 1, 2]->sort()" /> <!-- [1, 2, 3] -->
<echo value="['pear', 'Apple', 'fig']->sort()" /> <!-- ['Apple', 'fig', 'pear'] because case doesn't change the order -->
<let name="people" value="[{ name: 'Bo', age: 9 }, { name: 'Ada', age: 36 }]" />
<echo value="$people->sort(by: .age)->pluck(name)" /> <!-- ['Bo', 'Ada'] because 9 is less than 36 -->
<echo value="$people->sort(by: .age, order: desc)->pluck(name)" /> <!-- ['Ada', 'Bo'] -->
<echo value="[3, 1, 2]->sort(compare: fn(a, b) => $b - $a)" /> <!-- [3, 2, 1] because a larger b comes first -->
echo [3, 1, 2]->sort()                          // [1, 2, 3]
echo ['pear', 'Apple', 'fig']->sort()           // ['Apple', 'fig', 'pear'] because case doesn't change the order
$people = [{ name: 'Bo', age: 9 }, { name: 'Ada', age: 36 }]
echo $people->sort(by: .age)->pluck(name)       // ['Bo', 'Ada'] because 9 is less than 36
echo $people->sort(by: .age, order: desc)->pluck(name)   // ['Ada', 'Bo']
echo [3, 1, 2]->sort(compare: fn(a, b) => $b - $a)       // [3, 2, 1] because a larger b comes first
ParameterTakes
compare optionalfn
by optionalfn
order optionalone of these words: asc|desc

Arguments can be named: ->sort(…, by: …, order: …).

Example
<echo>{ [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 35 }]->sort(by: fn(p) => $p.age, order: desc)->map(fn(p) => $p.name) }</echo>
echo [{ name: 'Joan', age: 82 }, { name: 'Sam', age: 35 }]->sort(by: fn(p) => $p.age, order: desc)->map(fn(p) => $p.name)

#list->split(separator) → list

The list cut into lists at each separator item, which is dropped: ['tea', 'milk', '', 'juice']->split('') is [['tea', 'milk'], ['juice']]. The separator is a value (matched with ==) or a check such as .is_empty() or fn(item). Separators next to each other, or at the start or end, give empty lists.

->split(separator) cuts the list into lists wherever the separator item appears, and drops the separator. Give a value to match with ==, or a check that is true for the separator. A separator at the start or the end leaves an empty list there:

<let name="lines" value="['tea', 'milk', '', 'juice']" />
<echo value="$lines->split('')" /> <!-- [['tea', 'milk'], ['juice']] because '' is the separator -->
<echo value="$lines->split(.is_empty())" /> <!-- [['tea', 'milk'], ['juice']] because the check is true for '' -->
<echo value="[5, 0, 7, 8, 0]->split(0)" /> <!-- [[5], [7, 8], []] because the 0 at the end leaves an empty list after it -->
$lines = ['tea', 'milk', '', 'juice']
echo $lines->split('')              // [['tea', 'milk'], ['juice']] because '' is the separator
echo $lines->split(.is_empty())     // [['tea', 'milk'], ['juice']] because the check is true for ''
echo [5, 0, 7, 8, 0]->split(0)      // [[5], [7, 8], []] because the 0 at the end leaves an empty list after it
Example
<echo>{ ['tea', 'milk', '', 'juice']->split('') }</echo>
echo ['tea', 'milk', '', 'juice']->split('')

#list->sum(fn(item)?) → number

The total of the items (or of fn for each item).

->sum(fn(item)?) adds the items up. Given a function, it adds what the function gives for each. An empty list gives 0. Whole numbers stay exact at any size:

<echo value="[3, 5, 2]->sum()" /> <!-- 10 -->
<let name="basket" value="[{ item: 'tea', price: 3 }, { item: 'milk', price: 2 }]" />
<echo value="$basket->sum(.price)" /> <!-- 5 because 3 + 2 is 5 -->
<echo value="[]->sum()" /> <!-- 0 -->
echo [3, 5, 2]->sum()   // 10
$basket = [{ item: 'tea', price: 3 }, { item: 'milk', price: 2 }]
echo $basket->sum(.price)   // 5 because 3 + 2 is 5
echo []->sum()          // 0
ParameterTakes
fn optionalfn
Example
<echo>{ [{ price: 2.5 }, { price: 4 }]->sum(fn(item) => $item.price) }</echo>
echo [{ price: 2.5 }, { price: 4 }]->sum(fn(item) => $item.price)

#list->take(count: number) → list

The first count items.

->take(count) gives the first count items, or all of them when there are fewer:

<let name="podium" value="['ada', 'bo', 'cy', 'di']" />
<echo value="$podium->take(3)" /> <!-- ['ada', 'bo', 'cy'] -->
<echo value="$podium->take(9)" /> <!-- ['ada', 'bo', 'cy', 'di'] because there are only 4 -->
$podium = ['ada', 'bo', 'cy', 'di']
echo $podium->take(3)   // ['ada', 'bo', 'cy']
echo $podium->take(9)   // ['ada', 'bo', 'cy', 'di'] because there are only 4
ParameterTakes
count requirednumber
Example
<echo>{ [1, 2, 3, 4]->take(2) }</echo>
echo [1, 2, 3, 4]->take(2)

#list->take_while(fn(item, index?)) → list

The items from the start for as long as fn(item, index) is true.

->take_while(fn(item, index?)) keeps items from the start for as long as the function is true, and stops at the first that fails:

<let name="temperatures" value="[12, 14, 17, 9, 18]" />
<echo value="$temperatures->take_while(fn(degrees) => $degrees >= 10)" /> <!-- [12, 14, 17] because 9 stops it, even though 18 comes after -->
$temperatures = [12, 14, 17, 9, 18]
echo $temperatures->take_while(fn(degrees) => $degrees >= 10)   // [12, 14, 17] because 9 stops it, even though 18 comes after
ParameterTakes
fn requiredfn
Example
<echo>{ [2, 4, 5, 6]->take_while(fn(n) => $n->is_even()) }</echo>
echo [2, 4, 5, 6]->take_while(fn(n) => $n->is_even())

#list->to_map(fn(item)) → map

A map with fn(item) as each item's key.

->to_map(fn(item)) makes a map with each item under the key the function gives for it. When two items give the same key, the later one wins:

<let name="people" value="[{ id: 'a1', name: 'Ada' }, { id: 'b2', name: 'Bo' }]" />
<let name="by_id" value="$people->to_map(.id)" />
<echo value="$by_id.b2.name" /> <!-- 'Bo' because Bo is stored under b2 -->
$people = [{ id: 'a1', name: 'Ada' }, { id: 'b2', name: 'Bo' }]
$by_id = $people->to_map(.id)
echo $by_id.b2.name   // 'Bo' because Bo is stored under b2
ParameterTakes
fn requiredfn
Example
<echo>{ [{ id: 'j', name: 'Joan' }, { id: 's', name: 'Sam' }]->to_map(fn(p) => $p.id) }</echo>
echo [{ id: 'j', name: 'Joan' }, { id: 's', name: 'Sam' }]->to_map(fn(p) => $p.id)

#list->union(other: list, by?: fn(item)) → list

The items of both lists, each once: this list's first, then the new ones from other. Items match with ==, or by what by: gives for each.

->union(other, by?) gives the items of both lists, each once: this list's first, then the new ones from the other. Items match with ==, or by what by: gives for each:

<let name="mine" value="['tea', 'milk']" />
<let name="yours" value="['milk', 'juice']" />
<echo value="$mine->union($yours)" /> <!-- ['tea', 'milk', 'juice'] because milk is only kept once -->
$mine = ['tea', 'milk']
$yours = ['milk', 'juice']
echo $mine->union($yours)   // ['tea', 'milk', 'juice'] because milk is only kept once
ParameterTakes
other requiredlist
by optionalfn

Arguments can be named: ->union(…, by: …).

Example
<echo>{ [1, 2, 3]->union([3, 4]) }</echo>
echo [1, 2, 3]->union([3, 4])

#list->unique(by?: fn(item, index?)) → list

The list without duplicates, using strict equality (===), or keeping the first item for each by: fn(item, index) key: ->unique(by: .email).

->unique(by?) gives the list with each item once, keeping the first of any repeats. Items match with ===, so the number 1 and the text '1' are different. With by:, items match by what it gives:

<echo value="[3, 1, 3, 2, 1]->unique()" /> <!-- [3, 1, 2] -->
<let name="emails" value="['ADA@x.com', 'bo@x.com', 'ada@x.com']" />
<echo value="$emails->unique(by: .lower())" /> <!-- ['ADA@x.com', 'bo@x.com'] because the two ada addresses match in lower case -->
echo [3, 1, 3, 2, 1]->unique()   // [3, 1, 2]
$emails = ['ADA@x.com', 'bo@x.com', 'ada@x.com']
echo $emails->unique(by: .lower())   // ['ADA@x.com', 'bo@x.com'] because the two ada addresses match in lower case
ParameterTakes
by optionalfn
Example
<echo>{ [1, 2, 2, 3, 1]->unique() }</echo>
echo [1, 2, 2, 3, 1]->unique()

#list->window(size: number, step?: number) → list

Overlapping runs of size items, each starting step items after the last (1 by default): [1, 2, 3]->window(2) is [[1, 2], [2, 3]].

->window(size, step?) gives every run of size items next to each other. Each run starts step items after the last one, 1 unless you give another, so the runs overlap:

<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->window(2)" /> <!-- [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] because each pair starts one day later -->
<echo value="$week->window(2, 2)" /> <!-- [['mon', 'tue'], ['wed', 'thu']] because each pair starts two days later -->
$week = ['mon', 'tue', 'wed', 'thu']
echo $week->window(2)      // [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] because each pair starts one day later
echo $week->window(2, 2)   // [['mon', 'tue'], ['wed', 'thu']] because each pair starts two days later
ParameterTakes
size requirednumber
step optionalnumber

Arguments can be named: ->window(…, step: …).

Example
<echo>{ [1, 2, 3, 4]->window(2) }</echo>
echo [1, 2, 3, 4]->window(2)

#list->without(what: word) → list

The items that aren't of a type (->without(string)), or without the ones a filter of the items' type keeps (->without(prereleases)).

->without(what) keeps the items that aren't of a type, or, on a list of a native type, the ones its filter doesn't keep. It is the opposite of ->only():

<let name="mixed" value="[3, 'tea', 7, true]" />
<echo value="$mixed->without(number)" /> <!-- ['tea', true] because 3 and 7 are numbers -->

<let name="versions" type="semver[]" value="['1.2.0', '2.0.0-beta', '1.10.0']" />
<echo value="$versions->without(prereleases)" /> <!-- ['1.2.0', '1.10.0'] because 2.0.0-beta is a prerelease -->
$mixed = [3, 'tea', 7, true]
echo $mixed->without(number)   // ['tea', true] because 3 and 7 are numbers

$versions: semver[] = ['1.2.0', '2.0.0-beta', '1.10.0']
echo $versions->without(prereleases)   // ['1.2.0', '1.10.0'] because 2.0.0-beta is a prerelease
ParameterTakes
what requiredword
Example
<let name="loads" value="[1, 'two', 3]" />
<echo>{ $loads->without(string) }</echo>
$loads = [1, 'two', 3]
echo $loads->without(string)

#list->zip(other) → list

Pairs of items from both lists: [[a1, b1], [a2, b2]...].

->zip(other) pairs each item with the item at the same position in the other list. It stops at the end of the shorter list:

<let name="names" value="['ada', 'bo']" />
<let name="scores" value="[72, 91, 45]" />
<echo value="$names->zip($scores)" /> <!-- [['ada', 72], ['bo', 91]] because 45 has no name to pair with -->
$names = ['ada', 'bo']
$scores = [72, 91, 45]
echo $names->zip($scores)   // [['ada', 72], ['bo', 91]] because 45 has no name to pair with
Example
<echo>{ ['a', 'b']->zip([1, 2]) }</echo>
echo ['a', 'b']->zip([1, 2])

From KScript.Math

These need <import package="KScript.Math" />import KScript.Math. See KScript.Math.

#list->median() → number KScript.Math

The middle number in the list.
Example
<import package="KScript.Math" />
<echo>{ [3, 1, 4, 1, 5]->median() }</echo>
import KScript.Math
echo [3, 1, 4, 1, 5]->median()

#list->stdev() → number KScript.Math

The population standard deviation of the list.
Example
<import package="KScript.Math" />
<echo>{ [2, 4, 4, 4, 5, 5, 7, 9]->stdev()->round(digits: 3) }</echo>
import KScript.Math
echo [2, 4, 4, 4, 5, 5, 7, 9]->stdev()->round(digits: 3)

Methods from any