리스트는 값을 순서대로 보관합니다: ['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())와 같습니다.
필드는 값에 관한 단순한 정보로, 대괄호 없이 점으로 읽어요: $value.name. 메서드는 인수를 받거나 작업을 수행하며, ->로 호출하거나 $value->name(arguments)처럼 값을 파이프로 넘겨서 호출해요: $value |> name(arguments).
함수가 모든 항목에 대해 참이면 ->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이 항목 중 하나에 대해 참이면 true입니다(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
->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
항목들의 평균(또는 각 항목에 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
#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
->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인 항목을 고르는 모든 방법입니다: [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)을 채웁니다. 그다음 인덱스는 받지 않습니다.
#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
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
#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
->each(fn(item, index?))은 각 항목에 대해 함수를 호출하고, 함수가 돌려주는 값이 아니라 하는 일을 위해서입니다. 그리고 목록을 그대로 돌려주어 계속 이어서 호출할 수 있습니다. =>로 작성한 함수는 식 하나만 담으므로, 로그를 남기거나 저장하는 것처럼 무언가를 하는 호출에는 ->each()가 알맞습니다:
<let name="tasks" value="['wash', 'dry', 'fold']" />
<let name="same" value="$tasks->each(fn(task) => $log->info("Doing { $task }"))" />
<!-- logs Doing wash, Doing dry and Doing fold -->
<echo value="$same" /> <!-- ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on -->
$tasks = ['wash', 'dry', 'fold']
$same = $tasks->each(fn(task) => $log->info("Doing { $task }"))
// logs Doing wash, Doing dry and Doing fold
echo $same // ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on
각 항목에 대해 echo 같은 문장을 실행하려면 for 반복문을 쓰세요: for task at index in $tasks { echo "{ $index + 1 }. { $task }" }.
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 < 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
->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
항목의 인덱스(==로 비교)이거나, 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
#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
리스트에 있는 모든 숫자를 순서대로 가져옵니다. 숫자는 그대로 두고, 텍스트는 그 안에 있는 숫자를 가져오며, 안에 있는 리스트도 함께 읽습니다. 예를 들어 ['-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
어떤 타입의 항목(->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
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']]
항목이 ->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
항목들을 하나의 값으로 합쳐요. 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()는 과정의 모든 합계를 유지해요.
->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
항목들을 자리 수만큼 옮기고, 끝을 넘어가면 처음으로 돌아와요. [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
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
->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
->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
#list->sort(compare?: fn(a, b), by?: fn(item), order?: asc|desc)→ list
정렬된 복사본: by: fn(item)은 정렬 기준 키를 주며(->sort(by: .name)), order: desc는 가장 큰 값을 먼저 놓습니다. 대신 compare 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
각 구분자 항목에서 목록을 잘라 나눈 목록이며, 구분자는 버려집니다: ['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
중복을 제거한 목록입니다. 엄격한 동등성(===)을 사용하거나, 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
각 항목 묶음이 겹치며, 매번 이전 시작점에서 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
->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를 참고하세요.