Traduzido automaticamente do inglês, que é a versão original.
campos e métodos de list
Listas como [1, 2, 3]. Métodos que alteram uma lista retornam uma nova.
Uma lista guarda valores em ordem: ['tea', 'milk', 'juice'], [3, 7, 9], ou registros como [{ name: 'Ada', age: 36 }]. O primeiro item fica no índice 0, e um índice negativo conta a partir do fim, então $drinks[-1] é o último item.
Métodos de lista nunca alteram a lista sobre a qual são chamados. Um método como ->push() ou ->sort() gera uma nova lista, então você guarda o resultado em uma variável ou encadeia o próximo método nele:
<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']
Métodos que recebem uma função a chamam uma vez para cada item. A função recebe o item primeiro e, se você pedir, o índice do item em segundo: fn(drink) => ... ou fn(drink, index) => .... A dica no editor mostra o que um método passa, como ->reduce(fn(total, item), initial?). Quando você quer apenas um campo ou método de cada item, escreva com um ponto em vez de uma função completa: ->map(.name) equivale a ->map(fn(person) => $person.name), e ->filter(.is_empty()) equivale a ->filter(fn(text) => $text->is_empty()).
Um campo é um dado simples sobre o valor, lido com um ponto e sem colchetes: $value.name. Um método recebe argumentos ou executa alguma ação, e é chamado com ->: $value->name(arguments), ou com o valor passado por pipe: $value |> name(arguments).
Verdadeiro quando fn é verdadeiro para todos os itens.
->all(fn(item, index?)) é verdadeiro quando a função é verdadeira para todos os itens. Para no primeiro item que falha. Uma lista vazia dá true, pois nenhum item falha:
<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
Verdadeiro quando fn é verdadeira para algum item (ou, sem fn, se a lista não estiver vazia).
->any(fn(item, index?)?) é verdadeiro quando a função é verdadeira para pelo menos um item. Para no primeiro item que passa. Sem função, verifica se a lista tem algum item:
<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
O item em um índice; índices negativos contam a partir do fim.
->at(index) retorna o item em uma posição, contando a partir de 0. Um índice negativo conta de trás para frente, então -1 é o último item. Um índice além de qualquer extremidade dá null em vez de erro. $list[index] lê o mesmo item:
<let name="week" value="['mon', 'tue', 'wed']" />
<echo value="$week->at(0)" /> <!-- 'mon' because positions start at 0 -->
<echo value="$week->at(-1)" /> <!-- 'wed' because -1 is the last item -->
<echo value="$week->at(5)" /> <!-- null because there is no sixth item -->
$week = ['mon', 'tue', 'wed']
echo $week->at(0) // 'mon' because positions start at 0
echo $week->at(-1) // 'wed' because -1 is the last item
echo $week->at(5) // null because there is no sixth item
A média dos itens (ou de fn aplicada a cada item), ou null quando vazio.
->average(fn(item)?) soma os itens e divide pela quantidade. Dada uma função, calcula a média do que a função retorna para cada item. Uma lista vazia dá null, pois não há o que calcular a média:
<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
As células de uma lista de listas, como um ->grid(). Sozinho, ou com rows, todas as linhas; com columns, todas as colunas, de cima para baixo. row: escolhe uma linha e column: uma coluna, cada uma contada a partir de 0 (-1 é a última). Uma linha e uma coluna juntas dão a única célula onde se encontram. As linhas podem ter tamanhos diferentes: uma coluna pula as linhas curtas demais para alcançá-la. 'ab\ncd'->grid()->cells(columns) é [['a', 'c'], ['b', 'd']].
->cells(rows?, columns?, row:?, column:?) lê uma lista de listas, como um ->grid(), como uma tabela. Sozinho, ou com rows, retorna todas as linhas; com columns retorna todas as colunas, de cima para baixo. row: escolhe uma linha e column: uma coluna, cada uma contada a partir de 0, com -1 para a última, e os dois juntos dão a única célula onde se encontram. As linhas podem ter tamanhos diferentes: uma coluna pula as linhas curtas demais para alcançá-la.
<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) divide a lista em listas de size itens, em ordem. A última lista contém o que sobrou, então pode ser menor:
<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
Todas as formas de escolher size itens, sem importar a ordem, na ordem da lista: [1, 2, 3]->combinations(2) é [[1, 2], [1, 3], [2, 3]].
->combinations(size) retorna todas as formas de escolher size itens quando a ordem dos itens escolhidos não importa. Cada escolha mantém os itens na ordem da lista, e nenhum item é escolhido duas vezes na mesma escolha.
Escolhendo 2 de ['tea', 'milk', 'juice'] funciona assim: combine tea com cada item depois dele (milk, depois juice), depois combine milk com cada item depois dele (juice). juice não tem nada depois, então é só isso. ['milk', 'tea'] nunca aparece, pois é a mesma escolha que ['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
Um uso comum é verificar todos os pares, como encontrar os dois preços que somam um total:
<let name="prices" value="[15, 40, 25, 60]" />
<let name="pair" value="$prices->combinations(2)->find(fn(two) => $two->sum() == 65)" />
<echo value="$pair" /> <!-- [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is -->
$prices = [15, 40, 25, 60]
$pair = $prices->combinations(2)->find(fn(two) => $two->sum() == 65)
echo $pair // [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is
O número de escolhas cresce rápido, então, passando de um milhão de listas, ele para com um erro de Limit em vez de esgotar a memória.
Uma função com um parâmetro por item escolhido recebe os itens um a um, em qualquer tamanho: $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70) recebe cada par como cheaper e dearer, e ->combinations(3) preenche fn(first, second, third). Nesse caso, ela não recebe o índice.
#list->common(count?: number, least?: bool, by?: fn(item))→ list
Os itens que mais aparecem, do mais frequente para o menos, cada um uma vez e como estão (números continuam sendo números): [3, 7, 7, 9, 9, 9]->common(2) é [9, 7]. Com least, os mais raros vêm primeiro: ->common(1, least) é [3]. Empates mantêm a ordem da lista. Sem count, todos os itens distintos. Os itens são comparados com ==, ou pelo resultado de by: para cada um.
->common(count?, least, by?) conta quantas vezes cada item aparece e devolve os itens nessa ordem, cada um uma vez. Sem least, os mais comuns vêm primeiro; com least, os mais raros. count mantém essa quantidade a partir do início, e sem ele você recebe todos os itens distintos. Itens que aparecem o mesmo número de vezes mantêm a ordem em que apareceram pela primeira vez, e cada um volta como está, então números continuam sendo números:
<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: decide o que conta como o mesmo item. O item devolvido é o primeiro de seu tipo:
<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
Um mapa do resultado de fn para quantos itens o produziram: ['a', 'bb', 'cc']->count_by(->count()) é { 1: 1, 2: 2 }.
->count_by(fn(item)) agrupa os itens pelo que a função devolve para cada um, e conta cada grupo. O resultado é um mapa de cada resposta para sua contagem:
<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
Os itens que não estão em other, cada um uma vez e na ordem original. Os itens são comparados com ==, ou pelo resultado de by: para cada um.
->difference(other, by?) devolve os itens que não estão na outra lista, cada um uma vez e na ordem desta lista. Os itens são comparados com ==, ou pelo resultado que by: devolve para cada um:
<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?)) chama a função para cada item, pelo que ela faz e não pelo que devolve, e retorna a lista sem alterações para que você possa encadear outras chamadas. Uma função escrita com => tem apenas uma expressão, então ->each() serve para uma chamada que faz algo, como registrar ou salvar cada item:
<let name="tasks" value="['wash', 'dry', 'fold']" />
<let name="same" value="$tasks->each(fn(task) => $log->info("Doing { $task }"))" />
<!-- logs Doing wash, Doing dry and Doing fold -->
<echo value="$same" /> <!-- ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on -->
$tasks = ['wash', 'dry', 'fold']
$same = $tasks->each(fn(task) => $log->info("Doing { $task }"))
// logs Doing wash, Doing dry and Doing fold
echo $same // ['wash', 'dry', 'fold'] because ->each() gives back the list it was called on
Para executar instruções para cada item, como echo, escreva um laço for: for task at index in $tasks { echo "{ $index + 1 }. { $task }" }.
O primeiro item para o qual fn(item, index) é verdadeiro, ou, com last, o último; null se nenhum.
->find(fn(item, index?), last?) devolve o primeiro item para o qual a função é verdadeira, ou, com last, o último. Devolve null quando nenhum item passa:
<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
Mapeia cada item e, em seguida, achata cada lista de resultados em um nível.
->flat_map(fn(item, index?)) é ->map() para uma função que devolve uma lista: a lista de cada item é espalhada em uma única lista plana, em vez de ser mantida como uma lista de listas:
<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
->flatten() espalha as listas dentro de uma lista nela mesma, em um nível de profundidade. Uma lista dentro de uma lista dentro de outra lista mantém sua lista interna:
<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
Um mapa do resultado de fn para os itens que o produziram.
->group_by(fn(item)) organiza os itens em grupos pelo que a função devolve para cada um. O resultado é um mapa de cada resposta para os itens que a produziram, na ordem original:
<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() devolve, em vez disso, quantos itens há em cada grupo.
O índice de um item (comparado com ==), ou do primeiro item para o qual fn(item, index) é verdadeira; com last, o último. -1 quando não há nenhum.
->index_of(item, last?) devolve a posição do primeiro item igual ao informado (com ==), ou do primeiro item para o qual uma função é verdadeira. Com last, a busca começa pelo fim. Devolve -1 quando não há nenhum:
<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
Parâmetro
Recebe
itemobrigatório
qualquer valor
lastopcional
uma flag: last ou not last
Os argumentos podem ser nomeados: ->index_of(…, last: …).
->insert(index, item) devolve uma nova lista com o item inserido naquela posição; os itens a partir dali são deslocados uma posição. Um índice negativo conta a partir do fim, então -1 insere o item antes do penúltimo:
<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
Os argumentos podem ser nomeados: ->insert(…, item: …).
Exemplo
<echo>{ ['a', 'c']->insert(1, 'b') }</echo>
echo ['a', 'c']->insert(1, 'b')
#list->intersect(other: list, by?: fn(item))→ list
Os itens que também estão em other, cada um uma vez e na ordem. Os itens são comparados com ==, ou pelo que by: indicar para cada um.
->intersect(other, by?) devolve os itens que também estão na outra lista, cada um uma vez e na ordem desta lista. Os itens são comparados com ==, ou pelo resultado que by: devolve para cada um:
<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
Cada número da lista, em ordem: números permanecem como estão, texto fornece os números contidos nele, e listas internas também são lidas, então ['-3 4', 5]->numbers() é [-3, 4, 5]. Outros itens são ignorados.
->numbers() retorna todos os números da lista, em ordem. Números permanecem como estão, texto fornece os números escritos nele (como ->numbers() de text faz), e listas internas também são lidas. Qualquer outro item é ignorado:
<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
Os itens de um tipo (->only(semver), ->only(number)) ou que um filtro do tipo dos itens mantém (->only(releases) sobre um semver[]).
->only(what) mantém os itens de um tipo, escrito como uma palavra simples: ->only(number), ->only(string). Em uma lista de um tipo nativo, também aceita os filtros próprios desse tipo, como ->only(prereleases) em uma semver[]:
<let name="mixed" value="[3, 'tea', 7, true]" />
<echo value="$mixed->only(number)" /> <!-- [3, 7] because only 3 and 7 are numbers -->
<let name="versions" type="semver[]" value="['1.2.0', '2.0.0-beta', '1.10.0']" />
<echo value="$versions->only(prereleases)" /> <!-- ['2.0.0-beta'] because only that version has a -beta part -->
$mixed = [3, 'tea', 7, true]
echo $mixed->only(number) // [3, 7] because only 3 and 7 are numbers
$versions: semver[] = ['1.2.0', '2.0.0-beta', '1.10.0']
echo $versions->only(prereleases) // ['2.0.0-beta'] because only that version has a -beta part
Retorna [correspondentes, restantes], testando cada item uma vez.
->partition(fn(item, index?)) divide a lista em duas em uma única passagem: os itens para os quais a função é verdadeira, depois o restante. Retorna ambos como uma lista de duas listas:
<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
Cada ordenação de size itens (todos, por padrão), na ordem da lista: [1, 2, 3]->permutations(2) é [[1, 2], [1, 3], [2, 1], [2, 3], [3, 1], [3, 2]].
->permutations(size?) retorna cada ordenação dos itens. Diferente de ->combinations(), a ordem importa, então ['tea', 'milk'] e ['milk', 'tea'] aparecem ambos. Sem size, cada ordenação usa todos os itens:
<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']]
Acima de um milhão de ordenações, ela para com um erro de Limit.
#list->pluck(key: Self.fields|Self.fields[])→ list
Um campo de cada item, ou um mapa dos campos selecionados para cada item quando recebe uma lista de chaves.
->pluck(key) retorna um campo de cada item, em ordem. Dada uma lista de chaves, retorna um mapa apenas com esses campos para cada item. Um campo ausente resulta em 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
Onde um item está em uma lista de listas, como um ->grid(): cada célula igual a ele (comparada com ==), ou para a qual uma fn(célula) é verdadeira, como um ponto { row, column }, linha por linha e da esquerda para a direita. '#.\n.#'->grid()->positions_of('#') é [{ row: 0, column: 0 }, { row: 1, column: 1 }]. Procure um ponto com ->contains({ row: 1, column: 1 }).
->positions_of(item) retorna cada posição em que um item está em uma lista de listas, como um ->grid(), como pontos com um .row e uma .column, linha por linha e da esquerda para a direita. As células correspondem com ==, ou quando uma função dada no lugar é verdadeira para elas. Procure um ponto com ->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
Com ->combinations(2), uma função com dois parâmetros recebe cada par de pontos, um a um. Isto conta os quadrados cujos quatro cantos são todos árvores:
<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
Os itens multiplicados entre si (ou fn para cada item); 1 para uma lista vazia: [2, 3, 4]->product() resulta em 24.
->product(fn(item)?) multiplica os itens entre si, assim como ->sum() os soma. Dada uma função, multiplica o que a função retorna para cada um. Uma lista vazia retorna 1. Números inteiros permanecem exatos em qualquer tamanho:
<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
Combina os itens em um único valor: fn(total, item) retorna o próximo total a partir do anterior e do próximo item, começando em initial: [1, 2, 3]->reduce(fn(total, n) => $total + $n, 10) é 16. Sem initial, o primeiro item é o primeiro total, como ->scan() faz; uma lista vazia então resulta em null.
->reduce(fn(total, item), initial?) percorre a lista para produzir um único valor. A função recebe o total até então e o próximo item, e retorna o novo total. Com initial, esse é o primeiro total; sem ele, o primeiro item é:
<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
Uma lista vazia retorna initial, ou null sem ele. ->scan() mantém cada total ao longo do caminho.
->reject(fn(item, index?)) mantém os itens para os quais a função é falsa: o oposto de ->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
Uma nova lista com o item no índice substituído; contagens negativas contam a partir do fim.
->replace_at(index, item) retorna uma nova lista com o item naquela posição substituído. Um índice negativo conta a partir do fim, e um índice além do final é um erro de 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
Os itens são deslocados em posições, de forma circular: [1, 2, 3, 4]->rotate(1) é [2, 3, 4, 1], e um by negativo os desloca no sentido contrário, [1, 2, 3, 4]->rotate(-1) é [4, 1, 2, 3].
->rotate(by) desloca cada item by posições em direção ao início, e os itens que saem pela frente vão para o fim. Um by negativo muda o sentido:
<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
Como reduce(), mas guarda cada total parcial: [1, 2, 3]->scan(fn(total, n) => $total + $n) é [1, 3, 6]. Sem initial, o primeiro item inicia o total.
->scan(fn(total, item), initial?) funciona como ->reduce(), mas guarda cada total ao longo do caminho, para que você veja como o resultado vai sendo construído:
<let name="spending" value="[5, 2, 8, 1]" />
<echo value="$spending->scan(fn(total, amount) => $total + $amount)" /> <!-- [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1 -->
<echo value="$spending->scan(fn(total, amount) => $total - $amount, 20)" /> <!-- [15, 13, 5, 4] because a budget of 20 goes down by each amount -->
$spending = [5, 2, 8, 1]
echo $spending->scan(fn(total, amount) => $total + $amount) // [5, 7, 15, 16] because 5, then 5 + 2, then 7 + 8, then 15 + 1
echo $spending->scan(fn(total, amount) => $total - $amount, 20) // [15, 13, 5, 4] because a budget of 20 goes down by each amount
Every place a mask fits (->shapes(Tree), or ->shapes([Block, Ell]) for several), and every square, rectangle, line or circle (name one or several: ->shapes(square, circle, of: '#')) made by the cells that hold of: (a value, or a regex). It looks through text (each line a row, each character a cell, a blank line between layers), a list of values (one row), a grid ($grid[row][column]) or a 3D list ($cube[layer][row][column]); the built-in shapes also take a list of points { row, column }. A mask is a type that extends Mask: its layout is a picture, one character a cell, and each character matches a cell holding the same character, unless its symbols say otherwise (a value, a regex, a fn(cell), 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
Os itens após aqueles no início para os quais fn(item, index) é verdadeiro.
->skip_while(fn(item, index?)) pula itens do início enquanto a função for verdadeira, e depois mantém tudo a partir do primeiro item que falha, o que vier depois:
<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
Os itens do início até (sem incluir) end; posições negativas contam a partir do fim.
->slice(start, end?) retorna os itens da posição start até, sem incluir, a posição end, ou até o fim da lista. Posições negativas contam a partir do fim:
<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
Uma cópia ordenada: by: fn(item) fornece a chave de ordenação, ->sort(by: .name), e order: desc coloca o maior primeiro. Um compare fn(a, b) retorna negativo, 0 ou positivo no lugar.
->sort(compare?, by?, order?) retorna uma nova lista em ordem, do menor para o maior. Texto é ordenado alfabeticamente, ignorando maiúsculas e minúsculas. by: informa pelo que ordenar cada item, order: desc coloca o maior primeiro, e compare: recebe uma função de dois itens que retorna um número negativo quando o primeiro deve vir antes:
<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
A lista dividida em listas em cada item separador, que é descartado: ['tea', 'milk', '', 'juice']->split('') é [['tea', 'milk'], ['juice']]. O separador é um valor (comparado com ==) ou uma verificação como .is_empty() ou fn(item). Separadores vizinhos, ou no início ou no fim, geram listas vazias.
->split(separator) divide a lista em listas sempre que o item separador aparece, e descarta o separador. Informe um valor para comparar com ==, ou uma verificação que seja verdadeira para o separador. Um separador no início ou no fim deixa uma lista vazia ali:
<let name="lines" value="['tea', 'milk', '', 'juice']" />
<echo value="$lines->split('')" /> <!-- [['tea', 'milk'], ['juice']] because '' is the separator -->
<echo value="$lines->split(.is_empty())" /> <!-- [['tea', 'milk'], ['juice']] because the check is true for '' -->
<echo value="[5, 0, 7, 8, 0]->split(0)" /> <!-- [[5], [7, 8], []] because the 0 at the end leaves an empty list after it -->
$lines = ['tea', 'milk', '', 'juice']
echo $lines->split('') // [['tea', 'milk'], ['juice']] because '' is the separator
echo $lines->split(.is_empty()) // [['tea', 'milk'], ['juice']] because the check is true for ''
echo [5, 0, 7, 8, 0]->split(0) // [[5], [7, 8], []] because the 0 at the end leaves an empty list after it
->sum(fn(item)?) soma os itens. Dada uma função, soma o que a função retorna para cada um. Uma lista vazia dá 0. Números inteiros permanecem exatos em qualquer tamanho:
Os itens das duas listas, cada um uma vez: primeiro os desta lista, depois os novos de other. Os itens são comparados com ==, ou pelo que by: fornece para cada um.
->union(other, by?) retorna os itens das duas listas, cada um uma vez: primeiro os desta lista, depois os novos da outra. Os itens são comparados com ==, ou pelo que by: fornece para cada um:
<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
A lista sem duplicatas, usando igualdade estrita (===), ou mantendo o primeiro item de cada by: fn(item, index) chave: ->unique(by: .email).
->unique(by?) retorna a lista com cada item uma única vez, mantendo o primeiro de qualquer repetição. Os itens são comparados com ===, então o número 1 e o texto '1' são diferentes. Com by:, os itens são comparados pelo que ele retorna:
<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
Execuções sobrepostas de itens de tamanho size, cada uma começando step itens depois da última (1 por padrão): [1, 2, 3]->window(2) é [[1, 2], [2, 3]].
->window(size, step?) retorna todas as execuções de size itens seguidos. Cada execução começa step itens depois da última, 1 a menos que você informe outro valor, então as execuções se sobrepõem:
<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
Pares de itens de ambas as listas: [[a1, b1], [a2, b2]...].
->zip(other) combina cada item com o item na mesma posição na outra lista. Ele para no fim da lista mais curta:
<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
Exemplo
<echo>{ ['a', 'b']->zip([1, 2]) }</echo>
echo ['a', 'b']->zip([1, 2])
De KScript.Math
Estes precisam de <import package="KScript.Math" />import KScript.Math. Veja KScript.Math.