KScript ドキュメント
JA

言語

英語から自動翻訳されています。原文は英語です。

list のフィールドとメソッド

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

関数を引数に取るメソッドは、要素ごとに 1 回ずつ関数を呼び出します。関数には最初に要素が、必要に応じて 2 番目に要素のインデックスが渡されます: fn(drink) => ... または fn(drink, index) => ...。エディタのヒントには、->reduce(fn(total, item), initial?) のようにメソッドが渡す値が表示されます。各要素の 1 つのフィールドやメソッドだけが欲しい場合は、関数全体を書く代わりにドットで書けます: ->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

1 つの値にまとめる: 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 を返すときに true になります。最初に失敗した要素で評価を止めます。空のリストでは失敗する要素がないため、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 がいずれかの要素で true のとき true になります (fn を省略した場合は、リストが空でなければ true)。

->any(fn(item, index?)?) は、少なくとも 1 つの要素について関数が true を返すときに true になります。最初に成功した要素で評価を止めます。関数を省略した場合は、リストに要素が 1 つでもあるかを判定します:

<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 optionalfn
例
<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 requirednumber
例
<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 optionalfn
例
<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: は 1 つの行、column: は 1 つの列を選びます (どちらも 0 から数え、-1 は最後)。行と列を両方指定すると、その交点にある 1 つのセルを返します。行の長さが異なっていても構いません。列の取得では、その列まで届かない短い行はスキップされます。'ab\ncd'->grid()->cells(columns) は [['a', 'c'], ['b', 'd']] です。

->cells(rows?, columns?, row:?, column:?) は、->grid() のようなリストのリストを表として読み取ります。単独で、または rows と指定すると、すべての行を返します。columns と指定すると、上から下へすべての列を返します。row: は 1 つの行、column: は 1 つの列を選びます (どちらも 0 から数え、最後は -1)。両方を指定すると、その交点にある 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 requirednumber
例
<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 個選ぶすべての組み合わせを返します。各組み合わせの要素はリストの順序を保ち、同じ組み合わせ内で同じ要素が 2 回選ばれることはありません。

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

よくある用途は、すべての組を調べることです。たとえば、合計が特定の値になる 2 つの価格を見つける場合などです:

<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

組み合わせの数は急速に増えるため、100 万を超えるリストを返す場合は、メモリ不足になる代わりに Limit エラーで停止します。

引数をピックされた項目ごとに1つずつ持つ関数は、それらを1つずつ、任意のサイズで受け取ります。$prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70) は各ペアを cheaper と dearer として受け取り、->combinations(3) は fn(first, second, third) を埋めます。その場合、インデックスは受け取りません。

パラメーター受け取るもの
size requirednumber
例
<echo>{ [1, 2, 3]->combinations(2) }</echo>
echo [1, 2, 3]->combinations(2)

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

最も頻繁に現れる項目を、最も多いものから順に、それぞれ1回ずつ、そのままの形で返します(数値は数値のまま)。[3, 7, 7, 9, 9, 9]->common(2) は [9, 7] です。least を指定すると、代わりに最も少ないものが先頭に来ます。->common(1, least) は [3] です。同数の場合はリストの順序を保ちます。count を省略すると、すべての異なる項目を返します。項目の照合には == を使います。by: を指定すると、各項目に対して得られる値で照合します。

->common(count?, least, by?) は各項目が現れる回数を数え、その順序で項目を返します。各項目は1回ずつ返されます。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 optionalnumber
least optionalフラグ: 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) は、指定した値と等しい項目の数を数えます(== を使用)。関数を渡した場合は、その関数が真となる項目の数を数えます:

<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 に含まれない項目を、それぞれ1回ずつ、順序を保って返します。項目の照合には == を使います。by: を指定すると、各項目に対して得られる値で照合します。

->difference(other, by?) は、もう一方のリストに含まれない項目を、それぞれ1回ずつ、このリストの順序で返します。項目の照合には == を使うか、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?)) は各項目に対して関数を呼び出します。関数が返す値ではなく、その処理内容のために使います。そしてリストを変更せずに返すので、メソッドチェーンを続けられます。=> で書いた関数は式を1つだけ持つため、->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?)) は、関数が真となる項目を順序どおりに残します:

<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?) は、関数が真となる最初の項目を返します。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 optionalフラグ: 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() です。各項目のリストが1つのフラットなリストに展開されるので、リストのリストにはなりません:

<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() は、リスト内のリストを1階層分だけ展開します。リストの中のリストの中にあるリストは、内側のリストのまま残ります:

<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) が真となる最初の項目のインデックスです。last を指定すると最後の項目のインデックスになります。該当する項目がない場合は -1 です。

->index_of(item, last?) は、指定した値と等しい最初の項目の位置(== を使用)、または関数が真となる最初の項目の位置を返します。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 required任意の値
last optionalフラグ: 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

item を index に挿入した新しいリストを返します。

->insert(index, item) は、その位置に項目を挿入した新しいリストを返します。それ以降の項目は1つずつ後ろにずれます。負のインデックスは末尾から数えるので、-1 は最後から2番目の位置に項目を挿入します:

<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 requirednumber
item required任意の値

引数には名前を付けられます: ->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?) は、もう一方のリストにも含まれる項目を、それぞれ1回ずつ、このリストの順序で返します。項目の照合には == を使うか、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?) は項目を1つのテキストにまとめます。項目の間には区切り文字を入れ、別の区切り文字を指定しない限り ', ' を使います:

<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) を指定すると、その結果が最大のものを返します。例:->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) を指定すると、その結果が最小のものを返します。例:->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() は、リスト内のすべての数値を順番に返します。数値はそのまま残り、テキストからは(->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) は、1 つの型の項目だけを残します。型は単語だけで指定します: ->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 requiredword
例
<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

[一致するもの, 残り] を返します。各項目は一度だけ判定されます。

->partition(fn(item, index?)) は、リストを 1 回の処理で 2 つに分けます。関数が真になる項目と、それ以外の項目です。両方を、2 つのリストからなるリストとして返します:

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

並び順が 100 万通りを超えると、Limit エラーで停止します。

パラメーター受け取るもの
size optionalnumber
例
<echo>{ ['a', 'b', 'c']->permutations() }</echo>
echo ['a', 'b', 'c']->permutations()

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

各要素から 1 つのフィールド、またはキーのリストを渡した場合は選択したフィールドのマップ。

->pluck(key) は、各項目から 1 つのフィールドを順番に取り出します。キーのリストを渡すと、各項目からそれらのフィールドだけを取り出したマップを返します。存在しないフィールドは 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) を使うと、引数を 2 つ取る関数に、点のペアが 1 組ずつ渡されます。次の例は、4 つの角がすべて木である正方形を数えます:

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

項目を 1 つの値にまとめます: fn(total, item) は、直前の合計と次の項目から新しい合計を返し、initial から始まります: [1, 2, 3]->reduce(fn(total, n) => $total + $n, 10) は 16 になります。initial を省略すると、->scan() と同様に最初の項目が最初の合計になります。その場合、空のリストは null になります。

->reduce(fn(total, item), initial?) はリストを順に処理して 1 つの値にまとめます。関数は、それまでの合計と次の項目を受け取り、新しい合計を返します。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 optional任意の値

引数には名前を付けられます: ->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 requirednumber
例
<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 requirednumber
item required任意の値

引数には名前を付けられます: ->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] になり、負の値を指定すると逆方向に動きます。[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 requirednumber
例
<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 optional任意の値

引数には名前を付けることができます: ->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 optionalnumber
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

先頭の 1 件を除いたすべての件数です。

->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) が true となる要素を除いた残りの要素です。

->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 の直前までの要素です。負の位置は末尾からの位置を表します。

->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 を指定すると最大のものが先頭になります。代わりに、負・0・正を返す compare fn(a, b) を指定することもできます。

->sort(compare?, by?, order?) は、最小のものが先頭になるよう順序付けた新しいリストを返します。テキストは大文字小文字を区別せずにアルファベット順に並べられます。by: は各項目をどの値でソートするかを指定し、order: desc は最大のものを先頭にし、compare: は2つの項目を受け取り、最初の項目が先に来るべき場合に負の数を返す関数を取ります:

<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 optionalfn
例
<echo>{ [{ price: 2.5 }, { price: 4 }]->sum(fn(item) => $item.price) }</echo>
echo [{ price: 2.5 }, { price: 4 }]->sum(fn(item) => $item.price)

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

先頭から 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?)) → list

fn(item, index) が真である間の、先頭からの項目です。

->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)) は、各項目を関数が与えるキーの下に置いたマップを作ります。2つの項目が同じキーを返す場合は、後のものが優先されます:

<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

重複を除いたリストです。厳密等価(===)を使うか、by: fn(item, index) キーごとに最初の項目を残します: ->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 requirednumber
step optionalnumber

引数には名前を付けることができます: ->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 requiredword
例
<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 のメソッド