Other languages are translated automatically from English.
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()).
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).
->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
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
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
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
#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
->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
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.
#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
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
#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
->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("Doing { $task }"))" />
<!-- 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 }" }.
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 < 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
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
->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.
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
->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
#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
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
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
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
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.
#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
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
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
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.
->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
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
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
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
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), same for cells that all hold one value, or any for a cell that isn't part of the shape). A layout can be a regex too, which reads cells along a row, any length. With repeated, the mask is stamped again and again from the top left until it covers the input, the copies at the edges cut off: every copy must hold what the first does, and each match is the first copy, with copies, how many there were (a regex layout gives one match per size that fits, smallest first). blank: (a value, a regex or a fn(cell)) names the input cells that fit anything, and copies and same cells fill each other's blanks in. 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?, repeated?, blank?) 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 same for cells that must all hold one value and any for a cell that isn't part of the shape. A layout can be a regex instead (layout: /[roygbv]+/), which reads the cells along a row, any length. With repeated, the mask is stamped again and again from the top left to cover the input, cut off at the edges, and each match is the first copy with copies, how many were stamped (a regex layout gives the shortest cutter that fits). blank: (a value, a regex or a fn(cell)) names the input cells that fit anything, and copies and same cells fill each other's blanks in. For the built-in shapes, name one or several, and say which cells make them with of: (a value, a regex or a fn(cell)). 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 -->
<type name="Instructions" description="A printer's instructions: one or more colours." extends="Mask">
<field name="layout" default="/[roygbv]+/" />
</type>
<let name="cutter" value="['o', '?', '?', 'v', '?', '?', '?', 'y']->shapes(Instructions, repeated, blank: '?')->first()" />
<echo value="$cutter.points->count()" /> <!-- 5 because o??v? stamped and cut off agrees with every colour that can be read -->
$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
/// A printer's instructions: one or more colours.
type Instructions extends Mask {
layout: /[roygbv]+/
}
$cutter = ['o', '?', '?', 'v', '?', '?', '?', 'y']->shapes(Instructions, repeated, blank: '?')->first()
echo $cutter.points->count() // 5 because o??v? stamped and cut off agrees with every colour that can be read
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
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
#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
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
->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:
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
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
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
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
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.