KScript 文档
ZH

列出字段和方法

列表如 [1, 2, 3]。会改变列表的方法返回一个新列表。

列表按顺序保存值:['tea', 'milk', 'juice']、[3, 7, 9],或是诸如 [{ name: 'Ada', age: 36 }] 之类的记录。第一个元素的索引为 0,负数索引从末尾开始计数,因此 $drinks[-1] 指向最后一个元素。

列表方法从不修改其调用的列表本身。像 ->push() 或 ->sort() 这样的方法会返回一个新列表,因此你需要将结果保存到变量中,或将下一个方法链接在其后:

<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']

方法接受一个函数,并对每个元素各调用一次。函数首先接收该元素,如果需要,第二个参数是该元素的索引:fn(drink) => ... 或 fn(drink, index) => ...。编辑器中的提示会显示方法传递的内容,例如 ->reduce(fn(total, item), initial?)。如果你只想获取每个元素的某个字段或方法,可以用点号代替完整的函数:->map(.name) 等同于 ->map(fn(person) => $person.name),->filter(.is_empty()) 等同于 ->filter(fn(text) => $text->is_empty())。

了解列表的信息: count · count_of · is_empty · contains · index_of · any · all

取出元素: first · last · at · find · max · min · take · skip · slice · take_while · skip_while · pluck

保留部分项: filter · reject · only · without · partition · unique · difference · intersect · union

更改每一项: map · flat_map · each

添加、删除和重新排序: push · prepend · insert · replace_at · remove · remove_at · pop · reverse · sort · rotate

合并为单个值: sum · product · average · reduce · scan · join · common · count_by

分组与重塑: group_by · to_map · chunk · window · split · flatten · zip · cells · positions_of · shapes · combinations · permutations

字段是关于值的一个普通事实,用点号读取,不需要方括号:$value.name。方法会接收参数或执行操作,调用方式为 ->:$value->name(arguments),也可以把值通过管道传入:$value |> name(arguments)。

来自 KScript.Core

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

当 fn 对每一项都为真时返回真。

当函数对每一项都为真时,->all(fn(item, index?))为真。它会在遇到第一个不满足条件的项时停止。空列表返回true,因为不存在不满足的项:

<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
参数接受
fn 必填fn
示例
<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

当 fn 对任意一项返回真时为真(若不提供 fn,则列表非空时为真)。

->any(fn(item, index?)?) 在函数对至少一个元素为真时返回真。它在遇到第一个通过的元素时停止。若不提供函数,则判断列表中是否存在任何元素:

<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
参数接受
fn 可选fn
示例
<echo>{ [3, 8, 1]->any(fn(n) => $n > 5) }</echo>
echo [3, 8, 1]->any(fn(n) => $n > 5)

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

某索引处的项;负数从末尾计数。

->at(index) 按位置返回元素,位置从 0 开始计数。负数索引从末尾倒数,因此 -1 指向最后一个元素。超出任一端的索引返回 null,而不是报错。$list[index] 读取的是同一个元素:

<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
参数接受
index 必填number
示例
<echo>{ ['a', 'b', 'c']->at(-1) }</echo>
echo ['a', 'b', 'c']->at(-1)

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

这些项的平均值(或对每一项应用 fn 后的平均值);若为空则返回 null。

->average(fn(item)?) 将各项相加,再除以项数。给定一个函数时,它对每一项取函数结果后求平均值。空列表会返回null,因为没有可供求平均的内容:

<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
参数接受
fn 可选fn
示例
<echo>{ [4, 8, 9]->average() }</echo>
echo [4, 8, 9]->average()

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

列表的列表(如 a->grid())中的单元格。单独使用,或与 rows 一起使用时,返回每一行;与 columns 一起使用时,返回从上到下的每一列。row:选取一行;column:选取一列,编号从 0 开始(-1 表示最后一个)。同时指定行和列时,返回两者交叉处的那一个单元格。各行的长度可以不同:选取列时,会跳过长度不足以到达该列的行。'ab\ncd'->grid()->cells(columns) 的结果是 [['a', 'c'], ['b', 'd']]。

->cells(rows?, columns?, row:?, column:?) 读取列表的列表(例如 ->grid()),把它当作表格来处理。单独使用时,或与 rows 一起使用时,它会返回每一行;与 columns 一起使用时,它会从上到下返回每一列。row: 取出一行,column: 取出一列,行和列的索引都从 0 开始计数,-1 表示最后一个,两者结合即可得到它们交叉处的那一个单元格。各行的长度可以不同:取某一列时,会跳过长度不足以到达该列的行。

<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
参数接受
row 可选number
rows 可选标志:rows 或 not rows
column 可选number
columns 可选标志:columns 或 not columns

参数可以使用命名方式:->cells(…, rows: …, column: …)。

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

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

size列表中的项目。

->chunk(size) 将列表按顺序切分为每组 size 个元素的子列表。最后一组保留剩余元素,因此可能较短:

<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
参数接受
size 必需number
示例
<echo>{ [1, 2, 3, 4, 5]->chunk(2) }</echo>
echo [1, 2, 3, 4, 5]->chunk(2)

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

按列表顺序列出从中选取 size 个元素的所有组合,不考虑顺序:[1, 2, 3]->combinations(2) 的结果为 [[1, 2], [1, 3], [2, 3]]。

->combinations(size) 给出在所选项目的顺序无关紧要时,从中选取 size 个项目的所有方式。每种选取都按列表中的原有顺序保留项目,同一次选取中不会重复选取同一项目。

从['tea', 'milk', 'juice']中选2个的方法如下:将tea与其后的每一项配对(先是milk,然后是juice),再将milk与其后的每一项配对(即juice)。juice之后已经没有项了,所以到此为止。['milk', 'tea']不会出现,因为它与['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

一种常见用法是检查每一对元素,例如找出两个价格之和等于总额的组合:

<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

选项数量增长很快,因此超过一百万个列表后会以 Limit 错误停止,而不是耗尽内存。

参数为每个选中项各一个的函数会逐个获取它们,数量不限:$prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70) 将每对分别作为 cheaper 和 dearer 获取,->combinations(3) 填充 fn(first, second, third)。此时它不会获取索引。

参数接受
size 必需number
示例
<echo>{ [1, 2, 3]->combinations(2) }</echo>
echo [1, 2, 3]->combinations(2)

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

按出现次数从多到少给出各项,每项只出现一次,并保持原样(数字仍为数字):[3, 7, 7, 9, 9, 9]->common(2) 结果为 [9, 7]。使用 least 时则相反,最少出现的排在最前:->common(1, least) 结果为 [3]。次数相同则保持列表顺序。省略 count 时,返回所有不重复的项。项之间使用 == 比较,或通过 by: 为每项指定的比较方式进行匹配。

->common(count?, least, by?) 统计每个项出现的次数,并按该顺序返回各项,每项只出现一次。省略 least 时,出现最多的排在最前;使用 least 时,出现最少的排在最前。count 从前面保留指定数量的项,省略时返回所有不重复的项。出现次数相同的项保持它们首次出现的顺序,并且按原样返回,因此数字仍为数字:

<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: 决定什么算作相同的项。返回的是同类项中的第一个:

<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
参数接受
count 可选number
least 可选标志参数:least 或 not least
by 可选fn

参数可以命名:->common(…, least: …, by: …)。

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

#list->contains(item) → bool

当列表包含该项目时为 true。

当列表中存在与给定值相等的项时,->contains(item) 为 true。它使用 == 进行比较,因此数字 1 与文本 '1' 会相互匹配:

<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

若要判断是否有任意项通过某个测试,而不是等于某个值,请使用 ->any()。

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

#list->count() → number

项目的数量。

->count() 返回列表中的项数:

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

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

从 fn 的结果到得出该结果的项数的映射:['a', 'bb', 'cc']->count_by(->count()) 的结果为 { 1: 1, 2: 2 }。

->count_by(fn(item)) 按函数为每个项给出的结果对项进行分组,并统计每组的数量。结果是一个映射,从每个结果值映射到其计数:

<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
参数接受
fn 必填fn
示例
<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

统计函数结果为真的项目,或使用 == 统计等于某个值的项目。

->count_of(match) 统计等于某个值(使用 ==)的项的数量,或者,若给定一个函数,则统计使函数为 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
示例
<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

不在 other 中的项,每项只出现一次,并保持原有顺序。项之间使用 == 比较,或通过 by: 为每项指定的比较方式进行匹配。

->difference(other, by?) 返回不在另一列表中的项,每项只出现一次,并保持本列表的顺序。项之间使用 == 比较,或通过 by: 为每项给出的结果进行匹配:

<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
参数接受
other 必填list
by 可选fn

参数可以命名:->difference(…, by: …)。

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

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

对每个元素调用 fn,并返回该列表。

->each(fn(item, index?)) 为每个项调用该函数,关注的是它做了什么而不是返回什么,并原样返回列表,以便继续链式调用。使用 => 编写的函数只包含一个表达式,因此 ->each() 适合用于执行某些操作的调用,例如记录日志或保存每个项:

<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

若要为每个项运行语句,例如 echo,请编写 for 循环:for task at index in $tasks { echo "{ $index + 1 }. { $task }" }。

参数接受
fn 必填fn
示例
<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

fn(item, index) 为真的项目。

->filter(fn(item, index?)) 按顺序保留函数为 true 的项:

<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() 则保留其余的项。

参数接受
fn 必填fn
示例
<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

fn(item, index) 为真的第一个项目;若指定 last,则返回最后一个;若都不满足则返回 null。

->find(fn(item, index?), last?) 返回第一个使函数为 true 的项,若使用 last,则返回最后一个。若没有项通过,则返回 null:

<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
参数接受
fn 必填fn
last 可选标志参数:last 或 not last

参数可以命名:->find(…, last: …)。

示例
<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

第一项,否则为 null。

->first() 返回第一项;对于空列表则返回 null:

<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
示例
<echo>{ ['tea', 'coffee']->first() }</echo>
echo ['tea', 'coffee']->first()

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

先对每一项做映射,再将每个结果列表按一层展开。

当函数返回列表时,->flat_map(fn(item, index?)) 为 ->map():每个项的列表会展开合并为一个扁平列表,而不是保留为列表的列表:

<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
参数接受
fn 必填fn
示例
<echo>{ [1, 2]->flat_map(fn(n) => [$n, -$n]) }</echo>
echo [1, 2]->flat_map(fn(n) => [$n, -$n])

#list->flatten() → list

列表中的列表会被展开并并入其中。

->flatten() 将列表中的列表展开到其中,仅展开一层。列表中的列表再包含的列表会保持不变:

<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
示例
<echo>{ [[1, 2], [3], [4, 5]]->flatten() }</echo>
echo [[1, 2], [3], [4, 5]]->flatten()

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

从 fn 的结果到得出该结果的项的映射。

->group_by(fn(item)) 按函数为每个项给出的结果将项分组。结果是一个映射,从每个结果值映射到得出该结果的项(按顺序排列):

<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() 则改为给出每组中的数量。

参数接受
fn 必填fn
示例
<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

项的索引(使用 == 比较),或第一个使 fn(item, index) 为 true 的项的索引;若使用 last,则为最后一个。若不存在,则返回 -1。

->index_of(item, last?) 返回第一个与给定值相等的项(使用 == 比较)的位置,或第一个使函数为 true 的项的位置。使用 last 时则从末尾开始查找。若不存在,则返回 -1:

<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
参数接受
item 必填任意值
last 可选标志参数:last 或 not last

参数可以命名:->index_of(…, last: …)。

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

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

返回一个新列表,在 index 处插入 item。

->insert(index, item) 返回一个新列表,在指定位置插入该项;从该位置起的各项依次后移。负索引从末尾开始计数,因此 -1 会将该项插入到倒数第二项之前:

<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
参数接受
index 必填number
item 必填任意值

参数可以命名:->insert(…, item: …)。

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

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

同时存在于 other 中的项,每项只保留一次且保持顺序。项之间用 == 比较,或通过 by: 指定的键比较。

->intersect(other, by?) 返回同时存在于另一列表中的项,每项只出现一次,并保持本列表的顺序。项之间使用 == 比较,或通过 by: 为每项给出的结果进行匹配:

<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
参数接受
other 必填list
by 可选fn

参数可以命名:->intersect(…, by: …)。

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

#list->is_empty() → bool

当列表没有任何项时为 true。

当列表中没有任何项时,->is_empty() 为 true:

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

#list->join(separator?) → string

将各项连接成文本(默认分隔符为 ', ')。

->join(separator?) 将各项合并为一段文本,项与项之间使用分隔符,除非你指定其他分隔符,否则使用 ', ':

<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'
示例
<echo>{ ['a', 'b', 'c']->join(' / ') }</echo>
echo ['a', 'b', 'c']->join(' / ')

#list->last() → any

最后一项,若无则为 null。

->last() 返回最后一项,若列表为空则返回 null:

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

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

一个新列表,其中每个元素都应用 fn(item, index)。

->map(fn(item, index?)) 返回一个新列表,其中每一项为该函数对该项的结果,顺序不变:

<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']
参数接受
fn 必填fn
示例
<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

最大的项,或使用 by: fn(item) 时 by 值最大的项:->max(by: .score)。

->max(by?) 返回最大的一项;若给出 by:,则返回使 by: 值最大的那一项。对空列表返回 null:

<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
参数接受
by 可选fn
示例
<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

最小的项,或使用 by: fn(item) 时 by 值最小的项:->min(by: .price)。

->min(by?) 返回最小的一项;若给出 by:,则返回使 by: 值最小的那一项:

<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
参数接受
by 可选fn
示例
<echo>{ [4, 9, 2]->min() }</echo>
echo [4, 9, 2]->min()

#list->numbers() → number[]

列表中的每个数字,按顺序排列:数字保持不变,文本则取出其中的数字,内部的列表也会被读取,因此 ['-3 4', 5]->numbers() 为 [-3, 4, 5]。其他项会被跳过。

->numbers() 按顺序返回列表中的每个数字。数字保持不变,文本则取出其中写明的数字(与 text 的 ->numbers() 相同),内部的列表也会被读取。其他内容会被跳过:

<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
示例
<echo>{ ['-3 4', 5]->numbers() }</echo>
echo ['-3 4', 5]->numbers()

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

某一类型的项(->only(semver)、->only(number)),或经过类型筛选保留的项(对 semver[] 使用 ->only(releases))。

->only(what) 保留某一类型的项,写作单独的一个词:->only(number)、->only(string)。对原生类型的列表,它还可以使用该类型自身的筛选器,例如对 semver[] 使用 ->only(prereleases):

<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() 保留其余的项。

参数接受
what 必需word
示例
<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

返回 [matching, remaining],对每个项只测试一次。

->partition(fn(item, index?)) 一次遍历即把列表分成两部分:函数结果为真的项,以及其余的项。它将两者作为一个包含两个列表的列表返回:

<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
参数接受
fn 必填fn
示例
<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

按列表顺序给出 size 项的每一种排列(默认为全部项):[1, 2, 3]->permutations(2) 为 [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]]。

->permutations(size?) 返回项的每一种排列。与 ->combinations() 不同,顺序有影响,因此 ['tea', 'milk'] 和 ['milk', 'tea'] 都会出现。若不给出 size,每种排列都使用全部项:

<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']]

超过一百万种排列时,它会因 Limit 错误而停止。

参数接受
size 可选number
示例
<echo>{ ['a', 'b', 'c']->permutations() }</echo>
echo ['a', 'b', 'c']->permutations()

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

每个项中的一个字段;若给出键列表,则为每个项中所选字段组成的映射。

->pluck(key) 按顺序从每一项中取出一个字段。若给出键的列表,则为每一项返回仅包含这些字段的映射。缺失的字段返回 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
参数接受
key 必填Self.fields|Self.fields[]
示例
<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

去掉最后一项后的新列表。

->pop() 返回一个去掉最后一项的新列表:

<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

要读取最后一项,请使用 ->last()。

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

#list->positions_of(item) → list

当某项位于列表的列表中(例如 ->grid() 的结果)时:返回所有与其相等的单元格(使用 == 比较),或使函数 fn(cell) 为真的单元格,以 { row, column } 形式的点表示,按行、从左到右排列。'#.\n.#'->grid()->positions_of('#') 为 [{ row: 0, column: 0 }, { row: 1, column: 1 }]。使用 ->contains({ row: 1, column: 1 }) 可查找某个点。

->positions_of(item) 返回某项在列表的列表(例如 ->grid())中出现的每个位置,以带有 .row 和 .column 的点表示,按行、从左到右排列。单元格通过 == 匹配,或在给出函数并对其为真时匹配。使用 ->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

使用 ->combinations(2) 时,带两个参数的函数会逐对接收各个点。下面的代码统计四个角都是树的正方形数量:

<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
示例
<echo>{ ('#.' + @char_of(10) + '.#')->grid()->positions_of('#') }</echo>
echo ('#.' + @char_of(10) + '.#')->grid()->positions_of('#')

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

在开头添加项后得到的新列表。

->prepend(items...) 返回一个新列表,其中的项按给定顺序添加到开头:

<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']
示例
<echo>{ [2, 3]->prepend(1) }</echo>
echo [2, 3]->prepend(1)

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

所有项相乘的结果(或对每项应用 fn);空列表结果为 1:[2, 3, 4]->product() 结果为 24。

->product(fn(item)?) 将各项相乘,与 ->sum() 将各项相加相对。若给出函数,则对函数对每一项的结果相乘。空列表返回 1。整数在任意大小下都保持精确:

<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
参数接受
fn 可选fn
示例
<echo>{ [2, 3, 4]->product() }</echo>
echo [2, 3, 4]->product()

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

在末尾添加项后得到的新列表。

->push(items...) 返回一个新列表,其中的项按给定顺序添加到末尾:

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

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

将各项合并为一个值:fn(total, item) 根据上一个累计值和下一项计算新的累计值,从 initial 开始:[1, 2, 3]->reduce(fn(total, n) => $total + $n, 10) 为 16。若不给出 initial,则以第一项作为第一个累计值,与 ->scan() 相同;对空列表则返回 null。

->reduce(fn(total, item), initial?) 遍历列表以得出一个值。函数接收当前的累计值和下一项,并返回新的累计值。给出 initial 时,它即为第一个累计值;未给出时,则以第一项为第一个累计值:

<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

空列表返回 initial,若未给出则返回 null。->scan() 会保留过程中的每一个累计值。

参数接受
fn 必填fn
initial 可选任意值

参数可以命名:->reduce(…, initial: …)。

示例
<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

fn 返回 false 的项。

->reject(fn(item, index?)) 保留使函数为假的项,与 ->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
参数接受
fn 必填fn
示例
<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

不包含任何等于 item 的元素的新列表。

->remove(item) 返回一个新列表,去掉所有与给定项相等的项(若给出 ==):

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

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

返回一个新列表,去掉 index 处的项。

->remove_at(index) 返回一个新列表,去掉该位置上的项。负数索引从末尾开始计算:

<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
参数接受
index 必填number
示例
<echo>{ ['a', 'b', 'c']->remove_at(0) }</echo>
echo ['a', 'b', 'c']->remove_at(0)

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

返回一个新列表,将 index 处的项替换掉;负数索引从末尾计算。

->replace_at(index, item) 返回一个新列表,将该位置上的项替换掉。负数索引从末尾开始计算,超出末尾的索引会产生 Argument 错误:

<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
参数接受
index 必填number
item 必填任意值

参数可以命名:->replace_at(…, item: …)。

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

#list->reverse() → list

反转后的副本。

->reverse() 返回一个新列表,其中的项顺序相反:

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

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

各项按位置移动并首尾循环:[1, 2, 3, 4]->rotate(1) 为 [2, 3, 4, 1],负数的 by 则向另一方向移动,[1, 2, 3, 4]->rotate(-1) 为 [4, 1, 2, 3]。

->rotate(by) 将每一项向前移动 by 个位置,从前端移出的项放到末尾。负数的 by 则向相反方向移动:

<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
参数接受
by 必需number
示例
<echo>{ [1, 2, 3, 4]->rotate(1) }</echo>
echo [1, 2, 3, 4]->rotate(1)

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

与 ->reduce() 类似,但会保留每一步的累计值:[1, 2, 3]->scan(fn(total, n) => $total + $n) 的结果是 [1, 3, 6]。如果不提供 initial,则以第一个元素作为初始累计值。

->scan(fn(total, item), initial?) 的用法与 ->reduce() 相同,但会保留过程中的每个累计值,方便你看到结果是如何逐步累积的:

<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
参数接受
fn 必填fn
initial 可选任意值

参数可以有名称:->scan(…, initial: …)。

示例
<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
参数接受
mask 可选any
square 可选标志:square 或 not square
rectangle 可选rectangle 或 not rectangle 标志
line 可选一个标志:line 或 not line
circle 可选一个标志:circle 或 not circle
of 可选any
rotated 可选rotated或not rotated标志
size 可选number
radius 可选number
distance 可选straight|steps|moves之一:一个词

参数可以命名:->shapes(…, square: …, rectangle: …)。

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

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

除第一个之外的所有计数项。

->skip(count) 会为第一个之后的每一项添加 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
参数接受
count 必需number
示例
<echo>{ [1, 2, 3, 4]->skip(2) }</echo>
echo [1, 2, 3, 4]->skip(2)

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

开头之后、fn(item, index) 为真的各项。

->skip_while(fn(item, index?)) 会在函数持续返回真时跳过开头的元素,然后保留从第一个返回假的元素开始的全部内容,无论其后是什么:

<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
参数接受
fn 必填fn
示例
<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

从 start 到 end(不包括 end)的各项;负数位置从末尾开始计算。

->slice(start, end?) 返回从位置 start 开始、到位置 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
参数接受
start 必填number
end 可选number

参数可以命名:->slice(…, end: …)。

示例
<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

排序后的副本:by 参数接收一个函数 fn(item),返回用于排序的键,例如 ->sort(by: .name);order: desc 则让最大的项排在最前面。也可以改用比较函数 fn(a, b),它应返回负数、0 或正数。

->sort(compare?, by?, order?) 按顺序返回一个新列表,最小的排在最前。文本按字母顺序排序,忽略大小写。by: 指定每个元素用于排序的依据,order: desc 将最大的排在最前,compare: 接受一个包含两个元素的函数,当第一个元素应排在前面时,该函数返回负数:

<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
参数接受
compare 可选fn
by 可选fn
order 可选asc|desc之一:此处选择以下词语之一

参数可以使用名称:->sort(…, by: …, order: …)。

示例
<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

列表会在每个分隔符项处被切分,分隔符项本身会被丢弃:['tea', 'milk', '', 'juice']->split('') 的结果是 [['tea', 'milk'], ['juice']]。分隔符可以是一个值(用 == 匹配),也可以是 .is_empty() 或 fn(item) 这样的检查。相邻的分隔符,或位于开头和结尾的分隔符,会产生空列表。

->split(separator)会在分隔项出现的位置把列表切分成多个列表,并丢弃该分隔项。请给出一个用于与==匹配的值,或一个对分隔项为真的判断条件。若分隔项位于开头或结尾,则相应位置会得到一个空列表:

<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
示例
<echo>{ ['tea', 'milk', '', 'juice']->split('') }</echo>
echo ['tea', 'milk', '', 'juice']->split('')

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

各项的总和(或对每一项应用 fn 后的总和)。

->sum(fn(item)?) 把各项加起来。给定一个函数,它把函数对每一项给出的结果相加。空列表得到 0。整数在任何大小下都保持精确:

<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
参数接受
fn 可选fn
示例
<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) → 列表

前 count 个项。

->take(count) 返回前 count 个条目;如果条目不足,则返回全部条目:

<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
参数接受
count 必需number
示例
<echo>{ [1, 2, 3, 4]->take(2) }</echo>
echo [1, 2, 3, 4]->take(2)

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

只要 fn(item, index) 为 true,就从开头取出的项。

->take_while(fn(item, index?)) 只要函数为真,就一直保留开头的元素,并在遇到第一个不满足条件的元素时停止:

<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
参数接受
fn 必填fn
示例
<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

以 fn(item) 作为每个元素键的映射。

->to_map(fn(item)) 会根据函数为每个元素给出的键,创建一个映射,每个元素都存放在其对应的键下。当两个元素给出相同的键时,后面的元素会覆盖前面的元素:

<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
参数接受
fn 必填fn
示例
<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

两个列表的所有项目,每个只出现一次:先是本列表的项目,然后是来自 other 的新项目。项目通过 == 进行匹配,或通过 by: 为每个项目给出的结果进行匹配。

->union(other, by?) 按顺序返回两个列表中的所有项目,每项只保留一次:先是本列表的项目,然后是另一个列表中新出现的项目。项目的匹配依据是 ==,或者是 by: 为每个项目给出的值:

<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
参数接受
other 必填list
by 可选fn

参数可以命名:->union(…, by: …)。

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

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

不含重复项的列表,使用严格相等(===),或按以下方式为每一项保留第一个:fn(item, index) key: ->unique(by: .email).

->unique(by?) 返回列表,每个项目只保留一次,遇到重复项时保留第一个。项目通过 === 进行匹配,因此数字 1 和文本 '1' 是不同的。使用 by: 时,项目将按其返回的值进行匹配:

<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
参数接受
by 可选fn
示例
<echo>{ [1, 2, 2, 3, 1]->unique() }</echo>
echo [1, 2, 2, 3, 1]->unique()

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

按 size 个项目为一组生成重叠的连续片段,每个片段从上一个片段的最后一个项目之后的 step 个项目开始(默认为 1):[1, 2, 3]->window(2) 结果为 [[1, 2], [2, 3]]。

->window(size, step?) 返回每个由 size 个相邻项目组成的连续片段。每个片段在上一个片段的最后一个项目之后的 step 个项目处开始(除非你指定其他值,否则为 1),因此片段之间会有重叠:

<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
参数接受
size 必需number
step 可选number

参数可以命名:->window(…, step: …)。

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

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

不属于某种类型的项目(->without(string)),或去掉按项目类型过滤器保留下来的项目(->without(prereleases))。

->without(what) 保留不属于某种类型的项目,或者在原生类型列表中,保留其过滤器未保留的项目。它与 ->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
参数接受
what 必需word
示例
<let name="loads" value="[1, 'two', 3]" />
<echo>{ $loads->without(string) }</echo>
$loads = [1, 'two', 3]
echo $loads->without(string)

#list->zip(other) → list

两个列表中项目的配对:[[a1, b1], [a2, b2]...]。

->zip(other) 将每个项目与另一列表中相同位置的项目配对。它在较短列表结束处停止:

<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
示例
<echo>{ ['a', 'b']->zip([1, 2]) }</echo>
echo ['a', 'b']->zip([1, 2])

来自 KScript.Math

这些需要 <import package="KScript.Math" />import KScript.Math。参见 KScript.Math。

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

列表中的中位数。
示例
<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

列表的总体标准差。
示例
<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)

来自 any 的方法