KScript documentação
PT

Idioma

Traduzido automaticamente do inglês, que é a versão original.

A linguagem

Valores e métodos

Valores são strings, números, bools, listas, mapas, datas, funções e null, além dos valores que os pacotes adicionam (arquivos, respostas HTTP). Todo valor tem métodos, chamados com -> e encadeados:

<echo>{ $name->trim()->upper() }</echo>
<echo>{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }</echo>
<echo>{ $people |> sort(by: .name) |> first() }</echo>
<echo>{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }</echo>
echo "{ $name->trim()->upper() }"
echo "{ $people->filter(fn(p) => $p.age >= 18)->map(.name)->join(', ') }"
echo "{ $people |> sort(by: .name) |> first() }"
echo "{ @now()->add(days: 7)->format(pattern: 'd MMMM yyyy') }"

Use pluck(key) para ler um campo de cada item em ordem. Passe para pluck uma lista de chaves para produzir um novo mapa por item. As chaves podem ser nomes simples, strings entre aspas ou variáveis.

<let name="people" value="[{ name: 'Joan', age: 82 }, { name: 'Sam' }]" />
<let name="names" value="$people->pluck(name)" /> <!-- ['Joan', 'Sam'] -->
<let name="cards" value="$people->pluck([name, age])" /> <!-- [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }] -->
<let name="labels" value="$people->pluck(['name'])" /> <!-- [{ name: 'Joan' }, { name: 'Sam' }] -->
$people = [{ name: 'Joan', age: 82 }, { name: 'Sam' }]
$names = $people->pluck(name)          // ['Joan', 'Sam']
$cards = $people->pluck([name, age])   // [{ name: 'Joan', age: 82 }, { name: 'Sam', age: null }]
$labels = $people->pluck(['name'])     // [{ name: 'Joan' }, { name: 'Sam' }]

Uma chave de mapa ausente resulta em null. Registros tipados mantêm suas verificações de campo habituais. Uma lista de entrada vazia resulta em [], e pluck([]) resulta em um mapa vazio por item de entrada. Chaves repetidas aparecem uma vez, na ordem pedida.

Em uma lista, contains(value), index_of(value), remove(value) e count_of(value) comparam com ==. Por exemplo, [1, '1']->count_of(1) resulta em 2. unique() usa igualdade estrita (===), então [1, '1']->unique() mantém os dois itens.

is_empty() significa zero caracteres em uma string, zero itens em uma lista ou zero chaves em um mapa. Se você usou $text->is_empty() para aceitar entradas só com espaços, use $text->is_blank() para manter esse comportamento.

Texto ->is_empty() ->is_blank()
'' true true
' ' false true
'hello' false false

Um número é sempre escrito em dígitos simples, nunca com expoente: echo 10 ** 20 imprime 100000000000000000000 e echo 0.1 ** 20 imprime 0.00000000000000000001. Números inteiros são exatos em qualquer tamanho: 123456789 * 987654321 é 121932631112635269, 2 ** 100 é 1267650600228229401496703205376, e um id de 20 dígitos lido de texto ou JSON mantém todos os dígitos. +, -, *, %, **, / (quando a divisão é exata), ->sum(), ->product(), @gcd, @lcm e @factorial continuam exatos; uma fração, @sqrt e similares funcionam em ponto flutuante comum. Uma fração mostra 15 dígitos significativos, então 0.1 + 0.2 imprime 0.3. Um número inteiro pode crescer até cerca de 30.000 dígitos antes de parar com um erro de Limite.

Em texto, ->count() e as posições (em ->slice(), ->index_of() e $text[0]) contam a maioria dos caracteres como uma posição e um caractere como um emoji como duas. Nenhum método corta esse caractere ao meio: ->chars(), ->first(), ->last() e ->reverse() trabalham com caracteres inteiros como o leitor os vê, e ->slice() e ->truncate() movem um corte que cairia dentro de um deles para antes dele.

Um fato simples sobre um valor é um campo, lido com um ponto e sem colchetes, da mesma forma que as chaves de um mapa:

<import package="KScript.IO" />

<let name="day" value="'2026-11-19'->to_date()" />
<let name="file" value="@file(./notes.txt)" />
<echo>{ $day.year } { $day.weekday } { $file.name } { $file.size }</echo>
import KScript.IO

$day = '2026-11-19'->to_date()
$file = @file(./notes.txt)
echo "{ $day.year } { $day.weekday } { $file.name } { $file.size }"

Assim, $response.status, $file.size, $url.host e $e.status são campos, e tudo que recebe argumentos ou executa algo é um método: $response->convert(from: json), $file->read_text(), $day->format('yyyy'). Um nome que responde true ou false começa com is_ ou has_: $response.is_ok, $ip.is_private, $list->is_empty(), $map->has(key).

Uma duração de tempo é um número e uma unidade sem aspas, como 500ms, 30s, 10m, 2h, 1d ou 1w, combinados para mais (1h30m). Tudo que aceita uma duração de tempo aceita uma: wait(500ms), @api($url, options: { timeout: 30s }), $cache->set(key, value, ttl: 10m). Um número simples é sempre em segundos.

Anos e meses são y e mo (m são minutos): 1y, 6mo, 5y10mo. Um mês ou um ano não tem duração fixa, então eles movem datas pelo calendário ($date + 1mo mantém o dia do mês quando possível) e são recusados onde é preciso uma duração fixa, como em wait(1mo) ou 1mo.hours.

O editor completa os campos e métodos de cada tipo e mostra o que eles fazem. Para mudar o formato de um valor, como ler texto JSON ou escrever linhas como CSV, use ->convert(): veja Conversão entre formatos.

Datas

Os fatos de calendário de uma data são campos: .year, .month, .day, .weekday, .quarter, .day_of_year, .week (o número da semana ISO) e .days_in_month. .is_past, .is_future, .is_today e .is_weekend comparam a data com o momento atual, por isso servem para templates:

<let name="post" value="{ title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }" />
<echo value="$post.published_at.is_future ? 'Coming soon' : $post.title" />
$post = { title: 'Launch', published_at: '2030-01-01 09:00'->to_date() }
echo $post.published_at.is_future ? 'Coming soon' : $post.title

->start_of(unit) e ->end_of(unit) dão o primeiro e o último instante do day, week, month, quarter ou year em que uma data está, que é o que um relatório de "pedidos deste mês" precisa. Uma semana começa no primeiro dia do locale (segunda-feira em en-GB, domingo em en-US), ou no que week_start: indicar:

<let name="now" value="'2026-11-19 14:30'->to_date()" />
<let name="from" value="$now->start_of(month)" /> <!-- 2026-11-01 00:00 -->
<let name="to" value="$now->end_of(month)" /> <!-- 2026-11-30 23:59:59 -->
<let name="monday" value="$now->start_of(week, week_start: monday)" /> <!-- 2026-11-16 -->
$now = '2026-11-19 14:30'->to_date()
$from = $now->start_of(month)                      // 2026-11-01 00:00
$to = $now->end_of(month)                          // 2026-11-30 23:59:59
$monday = $now->start_of(week, week_start: monday) // 2026-11-16

A aritmética de calendário conta unidades inteiras. $date + 1y6mo move uma data por anos e meses, e o mesmo faz ->add(), que aceita qualquer combinação de years:, months:, weeks: e days: (->subtract() a move para trás). Um mês mantém o dia do mês quando possível, então 31 de janeiro mais um mês é o último dia de fevereiro. Para horas e minutos, some ou subtraia uma duração:

<let name="due" value="'2026-11-30'->to_date()->add(months: 1, days: 2)" /> <!-- 2027-01-01 -->
<let name="last_week" value="@today()->subtract(weeks: 1)" />
<let name="renewal" value="'2026-01-31'->to_date() + 1y1mo" /> <!-- 2027-02-28 -->
<let name="meeting" value="'2026-11-30 09:00'->to_date() + 1h30m" /> <!-- 10:30 -->
$due = '2026-11-30'->to_date()->add(months: 1, days: 2)   // 2027-01-01
$last_week = @today()->subtract(weeks: 1)
$renewal = '2026-01-31'->to_date() + 1y1mo                // 2027-02-28
$meeting = '2026-11-30 09:00'->to_date() + 1h30m          // 10:30

Uma data só se move por uma duração. $date + 1 é um erro, porque um número simples é sempre segundos, e o mesmo vale para somar um bool, uma lista ou outra data. Escreva a unidade ($date + 3d). O único lugar em que um número representa uma data é um timestamp Unix, segundos desde 1970, que ->to_date() lê e ->timestamp() devolve:

<let name="created" value="1795996800->to_date()" /> <!-- 2026-11-30 00:00 UTC -->
<let name="seconds" value="$created->timestamp()" /> <!-- 1795996800 -->
$created = 1795996800->to_date()       // 2026-11-30 00:00 UTC
$seconds = $created->timestamp()       // 1795996800

Subtrair uma data de outra dá o tempo exato entre elas como uma duração. ->since(other, in: unit) conta dias, semanas, meses ou anos inteiros, como faz um aniversário. ->is_same(other, unit) pergunta se duas datas caem no mesmo dia (o padrão), semana, mês, trimestre ou ano:

<let name="start" value="'2026-11-30 09:00'->to_date()" />
<let name="took" value="'2026-11-30 10:30'->to_date() - $start" /> <!-- 1h30m -->
<let name="born" value="'1990-12-01'->to_date()" />
<let name="age" value="'2026-11-19'->to_date()->since($born, in: years)" /> <!-- 35 -->
<let name="same" value="@today()->is_same(@now(), day)" /> <!-- true -->
$start = '2026-11-30 09:00'->to_date()
$took = '2026-11-30 10:30'->to_date() - $start         // 1h30m
$born = '1990-12-01'->to_date()
$age = '2026-11-19'->to_date()->since($born, in: years) // 35
$same = @today()->is_same(@now(), day)                  // true

Now vem do relógio do computador, então em testes @with_clock(date, fn) fixa esse valor para @now(), @today(), os campos acima e @format_relative().

Trabalhando com texto

Texto tem funções auxiliares para as tarefas que aparecem repetidamente: mudar a capitalização de um nome, cortar em um separador, limpar espaços e assinar um payload.

<echo value="'Order Total'->case(snake)" /> <!-- order_total -->
<echo value="'order_total'->case(camel)" /> <!-- orderTotal -->
<echo value="'order total'->case(pascal)" /> <!-- OrderTotal -->
<echo value="'orderTotal'->case(kebab)" /> <!-- order-total -->

<let name="email" value="'joan@example.com'" />
<echo>{ $email->before('@') } at { $email->after('@') }</echo> <!-- joan at example.com -->
<echo value="'archive.tar.gz'->after('.', last)" /> <!-- gz -->

<echo value="'  too   many    spaces '->squish()" /> <!-- too many spaces -->
<let name="words" value="'Hello, world!'->words()" /> <!-- ['Hello', 'world'] -->
<echo value="'4242424242424242'->mask('*', keep_end: 4)" />
echo 'Order Total'->case(snake)           // order_total
echo 'order_total'->case(camel)           // orderTotal
echo 'order total'->case(pascal)          // OrderTotal
echo 'orderTotal'->case(kebab)            // order-total

$email = 'joan@example.com'
echo "{ $email->before('@') } at { $email->after('@') }" // joan at example.com
echo 'archive.tar.gz'->after('.', last)  // gz

echo '  too   many    spaces '->squish()   // too many spaces
$words = 'Hello, world!'->words()       // ['Hello', 'world']
echo '4242424242424242'->mask('*', keep_end: 4)

->before() e ->after() cortam no primeiro separador, ou no último com last, e devolvem o texto inteiro quando o separador não existe. ->wrap(width: 60) quebra o texto entre palavras para caber em uma largura, como @terminal_width(). ->is_numeric() é verdadeiro para textos como '42' ou '-3.5'.

->contains(), ->starts_with(), ->ends_with(), ->index_of() (o último com last) e ->replace() diferenciam maiúsculas de minúsculas. Use ignore_case para comparar sem essa diferença:

<let name="query" value="'TEA'" />
<echo value="'Green tea'->contains($query, ignore_case)" /> <!-- true -->
$query = 'TEA'
echo 'Green tea'->contains($query, ignore_case) // true

Para verificar um webhook, calcule a assinatura com ->hmac(key) (SHA-256 por padrão, ou sha1 ou sha512) e compare com @secure_equals(), que leva o mesmo tempo independentemente de quanto dos dois coincide:

<let name="body" value="'{&quot;id&quot;: 1}'" />
<let name="signature" value="$body->hmac('whsec_test')" />
<echo value="@secure_equals($signature, $body->hmac('whsec_test'))" /> <!-- true -->
$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo @secure_equals($signature, $body->hmac('whsec_test')) // true

->md5(), ->sha1(), ->sha256() e ->sha512() retornam hashes em hexadecimal. @escape_regex(text) escapa o que o usuário digitou, para que um padrão montado a partir disso corresponda apenas a esse texto.

Listas e mapas

Listas são comparadas como conjuntos com ->difference(other), ->intersect(other) e ->union(other). Cada uma mantém a ordem da primeira lista, retorna cada item uma vez e compara os itens com ==, ou pelo resultado de by: para cada um:

<let name="left" value="[1, 2, 3, 4]->difference([2, 4])" /> <!-- [1, 3] -->
<let name="both" value="['tea', 'milk']->union(['milk', 'sugar'])" /> <!-- ['tea', 'milk', 'sugar'] -->
<let name="people" value="[{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]" />
<let name="kept" value="$people->intersect([{ id: 2 }], by: fn(p) => $p.id)" /> <!-- [{ id: 2, name: 'Bo' }] -->
$left = [1, 2, 3, 4]->difference([2, 4])            // [1, 3]
$both = ['tea', 'milk']->union(['milk', 'sugar'])   // ['tea', 'milk', 'sugar']
$people = [{ id: 1, name: 'Ada' }, { id: 2, name: 'Bo' }]
$kept = $people->intersect([{ id: 2 }], by: fn(p) => $p.id) // [{ id: 2, name: 'Bo' }]

->count_by(fn) conta os itens de cada chave, ->take_while(fn) e ->skip_while(fn) param no primeiro item que falha, ->window(size, step?) retorna sequências sobrepostas, e ->replace_at(index, item) retorna uma cópia com um item alterado:

<let name="counts" value="['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first())" /> <!-- { a: 2, b: 1 } -->
<let name="pairs" value="['mon', 'tue', 'wed', 'thu']->window(2)" /> <!-- [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']] -->
<let name="fixed" value="['tea', 'tae', 'milk']->replace_at(1, 'juice')" /> <!-- ['tea', 'juice', 'milk'] -->
$counts = ['apple', 'avocado', 'banana']->count_by(fn(fruit) => $fruit->first()) // { a: 2, b: 1 }
$pairs = ['mon', 'tue', 'wed', 'thu']->window(2)  // [['mon', 'tue'], ['tue', 'wed'], ['wed', 'thu']]
$fixed = ['tea', 'tae', 'milk']->replace_at(1, 'juice') // ['tea', 'juice', 'milk']

Mais e menos comuns: common

->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 menos comuns. count mantém apenas essa quantidade 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 aparecem pela primeira vez na lista, e cada item 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 2 times, 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(2)" /> <!-- ['apple', 'fig'] because those are the top 2 -->
<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 2 times, 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(2)         // ['apple', 'fig'] because those are the top 2
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. Aqui 'Tea' e 'tea' são contados juntos porque ambos viram 'tea' em minúsculas, e o que apareceu primeiro é o que você recebe de volta:

<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, twice -->
$drinks = ['Tea', 'milk', 'tea']
echo $drinks->common(1, by: fn(drink) => $drink->lower()) // ['Tea'] because 'Tea' and 'tea' count as one, twice

Para multiplicar os três números mais comuns, obtenha-os com ->common(3) e multiplique com ->product():

<let name="readings" value="[12, 7, 12, 9, 7, 12, 3]" />
<let name="top" value="$readings->common(3)" /> <!-- [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3 -->
<echo value="$top->product()" /> <!-- 756 because 12 * 7 * 9 is 756 -->
$readings = [12, 7, 12, 9, 7, 12, 3]
$top = $readings->common(3)   // [12, 7, 9] because 12 occurs 3 times, 7 twice, then 9 comes before 3
echo $top->product()         // 756 because 12 * 7 * 9 is 756

Mapas têm os mesmos callbacks das listas, recebendo primeiro o valor e depois a chave: ->filter(), ->reject(), ->any(), ->all(), ->find() (que retorna { key, value }), ->reduce(), ->sort(by:) e ->map(). ->map_keys(fn) renomeia cada chave, recebendo a chave e depois o valor:

<let name="stock" value="{ apples: 3, pears: 0, plums: 2 }" />
<let name="empty" value="$stock->reject(fn(n) => $n > 0)" /> <!-- { pears: 0 } -->
<let name="order" value="$stock->sort(by: fn(n) => $n, order: desc)->keys()" /> <!-- ['apples', 'plums', 'pears'] -->
<let name="renamed" value="{ first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel))" /> <!-- { firstName: 'Ada' } -->
$stock = { apples: 3, pears: 0, plums: 2 }
$empty = $stock->reject(fn(n) => $n > 0)               // { pears: 0 }
$order = $stock->sort(by: fn(n) => $n, order: desc)->keys()  // ['apples', 'plums', 'pears']
$renamed = { first_name: 'Ada' }->map_keys(fn(key) => $key->case(camel)) // { firstName: 'Ada' }

Convertendo entre formatos: convert

Dados passam de um formato para outro o tempo todo: uma API responde em JSON, um arquivo de configuração é YAML, uma planilha é salva como CSV. Todo valor tem um único método para tudo isso, ->convert(), e ele se lê como uma frase: converta de este formato, para aquele.

from: lê um texto escrito em um formato e devolve os valores contidos nele. to: escreve um valor em um formato. Passe os dois para converter diretamente um formato em outro.

Formato from: lê to: escreve
json mapas, listas, textos, números texto json
yaml mapas, listas, textos, números texto yaml
csv uma lista de linhas texto csv
markdown, latex um documento com KScript.Document
html de Markdown com KScript.Markdown, de documentos com KScript.Document

Lendo texto: from

from: aceita texto, um bloco de texto como um bloco ```yaml ou ```csv, um valor json ou csv, ou uma resposta HTTP (seu corpo):

<let name="order" value="'{&quot;fruit&quot;: &quot;apple&quot;, &quot;count&quot;: 3}'->convert(from: json)" />
<echo value="$order.count" /> <!-- 3 because the json text is now a map with a count key -->

<let name="settings">```yaml
    theme: dark
    size: 12
    ```</let>
<echo value="$settings->convert(from: yaml).size" /> <!-- 12 because the yaml is read into a map -->
$order = '{"fruit": "apple", "count": 3}'->convert(from: json)
echo $order.count   // 3 because the json text is now a map with a count key

$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml).size   // 12 because the yaml is read into a map

CSV tem uma linha de cabeçalho por padrão, que nomeia as chaves de cada linha. Escreva not header quando toda linha for dado, e cada linha será então uma lista de suas células:

<let name="prices">```csv
    fruit,price
    apple,3
    plum,5
    ```</let>
<echo value="$prices->convert(from: csv)[0].fruit" /> <!-- 'apple' because the header line names the fruit column -->
<echo value="$prices->convert(from: csv, not header)[0]" /> <!-- ['fruit', 'price'] because without a header the first line is a row too -->
$prices = ```csv
fruit,price
apple,3
plum,5
```
echo $prices->convert(from: csv)[0].fruit       // 'apple' because the header line names the fruit column
echo $prices->convert(from: csv, not header)[0] // ['fruit', 'price'] because without a header the first line is a row too

Verificando contra um tipo: as

as: verifica o que foi lido contra um tipo e o transforma em registros, de modo que um campo ausente ou errado seja um erro na linha que o leu, e não uma surpresa depois. Uma lista de registros é escrita como uma declaração a escreve, Fruit[]:

<type name="Fruit">
  <field name="fruit" type="string" />
  <field name="price" type="int" />
</type>

<let name="prices">```csv
    fruit,price
    apple,3
    plum,5
    ```</let>
<let name="fruits" value="$prices->convert(from: csv, as: Fruit[])" />
<echo value="$fruits[0].price + 1" /> <!-- 4 because as: Fruit[] turned the '3' cell into the int 3 -->
type Fruit {
  fruit: string
  price: int
}

$prices = ```csv
fruit,price
apple,3
plum,5
```
$fruits = $prices->convert(from: csv, as: Fruit[])
echo $fruits[0].price + 1   // 4 because as: Fruit[] turned the '3' cell into the int 3

Escrevendo um formato: to

to: escreve qualquer valor: mapas e listas como JSON ou YAML, e uma lista de linhas como CSV. indented espalha o JSON em várias linhas, e headers: escolhe e ordena as colunas do CSV:

<let name="basket" value="[{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]" />

<echo value="$basket->convert(to: json)" /> <!-- [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line -->
<echo value="$basket->convert(to: json, indented)" /> <!-- the same json, one key a line, for people to read -->
<echo value="$basket->convert(to: csv, headers: ['count'])" /> <!-- "count", then "3" and "5" because only the count column is asked for -->
$basket = [{ fruit: 'apple', count: 3 }, { fruit: 'plum', count: 5 }]

echo $basket->convert(to: json)                       // [{"fruit":"apple","count":3},{"fruit":"plum","count":5}] on one line
echo $basket->convert(to: json, indented)             // the same json, one key a line, for people to read
echo $basket->convert(to: csv, headers: ['count'])    // "count", then "3" and "5" because only the count column is asked for

Os dois de uma vez

Passe from: e to: juntos para converter um formato em outro sem manipular os valores no meio do caminho:

<let name="settings">```yaml
    theme: dark
    size: 12
    ```</let>
<echo value="$settings->convert(from: yaml, to: json)" /> <!-- {"theme":"dark","size":12} because the yaml is read, then written as json -->
$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml, to: json)   // {"theme":"dark","size":12} because the yaml is read, then written as json

Atalhos: from e to

Quando você só lê ou só escreve, ->from(type: json) e ->to(type: csv) dizem o mesmo em menos palavras. Eles aceitam as mesmas opções de ->convert():

<let name="order" value="'{&quot;fruit&quot;: &quot;apple&quot;}'->from(type: json)" />
<echo value="$order.fruit" /> <!-- 'apple' because ->from(type: json) is ->convert(from: json) -->
<echo value="[{ fruit: 'plum' }]->to(type: json)" /> <!-- [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json) -->
$order = '{"fruit": "apple"}'->from(type: json)
echo $order.fruit                        // 'apple' because ->from(type: json) is ->convert(from: json)
echo [{ fruit: 'plum' }]->to(type: json) // [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json)

->convert() é a única forma de converter um formato, então as formas antigas de um método por formato (->json(), ->yaml(), ->csv(), ->markdown(), ->to_json(), ->to_yaml(), ->to_csv(), e os ->html(), ->latex() e ->markdown() de um documento) são erros que mostram o ->convert() a escrever no lugar, com uma correção no editor.

Lendo texto estruturado

Dados muitas vezes chegam como texto: um registro por linha, grupos de linhas separados por uma linha em branco, ou um desenho feito com caracteres. Estes métodos transformam esse texto em listas com as quais você pode trabalhar.

Linhas e blocos

->lines() devolve um texto por linha. ->blocks() divide o texto nas linhas em branco, então cada bloco é um grupo de linhas. Uma quebra de linha simples fica dentro do bloco; apenas uma linha vazia inicia um novo:

<let name="pantry">```text
    tea
    milk

    flour
    sugar
    eggs
    ```</let>

<let name="shelves" value="$pantry->blocks()" />
<!-- ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block -->

<let name="counts" value="$shelves->map(.lines()->count())" />
<!-- [2, 3] because the first block has 2 lines and the second has 3 -->
$pantry = ```text
tea
milk

flour
sugar
eggs
```

$shelves = $pantry->blocks()
// ['tea\nmilk', 'flour\nsugar\neggs'] because the blank line after milk starts a second block

$counts = $shelves->map(.lines()->count())
// [2, 3] because the first block has 2 lines and the second has 3

.lines() no lugar de uma função é um atalho para fn(block) => $block->lines(): o método é chamado em cada item, assim como .name lê o campo de cada item. Funciona em qualquer lugar onde uma função vai, como em ->filter(.is_empty()) ou ->sort(by: .age).

Dividindo uma lista: split

Quando você já tem uma lista, ->split(separator) a corta em listas sempre que o item separador aparece, e descarta o separador. Passe um valor para comparar com ==, ou uma verificação que seja verdadeira para o separador:

<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 a separator 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 a separator at the end leaves an empty list after it

->split() em texto corta o texto; ->split() em uma lista corta a lista.

Números em texto: numbers

->numbers() devolve todos os números escritos no texto, em ordem, para que você não precise de um padrão para isso. Um sinal de menos conta como sinal quando está logo antes de um número, sem nada colado à sua esquerda, como em x=-3; entre dois números, como em 1-3, é um hífen, então você obtém 1 e 3:

<echo value="'move 3 boxes from -1 to 12'->numbers()" /> <!-- [3, -1, 12] because -1 has a space before its minus -->
<echo value="'pages 4-9'->numbers()" /> <!-- [4, 9] because the minus joins 4 and 9, so it is a dash -->
<echo value="'price 2.50, qty 4'->numbers()" /> <!-- [2.5, 4] -->
echo 'move 3 boxes from -1 to 12'->numbers()  // [3, -1, 12] because -1 has a space before its minus
echo 'pages 4-9'->numbers()                   // [4, 9] because the minus joins 4 and 9, so it is a dash
echo 'price 2.50, qty 4'->numbers()           // [2.5, 4]

Imagens em caracteres: grid

->grid() transforma linhas de caracteres em linhas de caracteres individuais, então $grid[row][column] é um único caractere. A linha 0 é a linha de cima e a coluna 0 é o primeiro caractere:

<let name="garden">```text
    #.#
    ..#
    ```</let>

<let name="plot" value="$garden->grid()" />
<!-- [['#', '.', '#'], ['.', '.', '#']] -->
<echo value="$plot[0][1]" /> <!-- '.' because row 0 is '#.#' and column 1 is its second character -->
<echo value="$plot[1][2]" /> <!-- '#' because row 1 is '..#' and column 2 is its last character -->
$garden = ```text
#.#
..#
```

$plot = $garden->grid()
// [['#', '.', '#'], ['.', '.', '#']]
echo $plot[0][1]   // '.' because row 0 is '#.#' and column 1 is its second character
echo $plot[1][2]   // '#' because row 1 is '..#' and column 2 is its last character

Percorrendo linhas e colunas: cells

->cells() lê uma grade como você leria uma tabela. Sozinho, ou com rows, devolve todas as linhas; com columns devolve todas as colunas, de cima para baixo. É assim que você percorre uma grade em qualquer direção:

<let name="garden">```text
    #.#
    ..#
    ```</let>

<let name="plot" value="$garden->grid()" />

<for each="row" in="$plot->cells(rows)">
  <echo value="$row->join('')" />
</for>
<!-- '#.#' then '..#' because each row is one line of the picture -->

<for each="column" in="$plot->cells(columns)">
  <echo value="$column->join('')" />
</for>
<!-- '#.' then '..' then '##' because each column reads one character from every line, top to bottom -->

<echo value="$plot->cells(columns)->map(fn(column) => $column->count_of('#'))" />
<!-- [1, 0, 2] because only the last column has a # in both rows -->
$garden = ```text
#.#
..#
```

$plot = $garden->grid()

for row in $plot->cells(rows) {
  echo $row->join('')
}
// '#.#' then '..#' because each row is one line of the picture

for column in $plot->cells(columns) {
  echo $column->join('')
}
// '#.' then '..' then '##' because each column reads one character from every line, top to bottom

echo $plot->cells(columns)->map(fn(column) => $column->count_of('#'))
// [1, 0, 2] because only the last column has a # in both rows

row: escolhe uma linha e column: uma coluna, ambas contadas a partir de 0, e -1 é a última. Passe as duas para obter a única célula onde elas se encontram:

<let name="garden">```text
    #.#
    ..#
    ```</let>

<let name="plot" value="$garden->grid()" />
<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, and both lines end in # -->
<echo value="$plot->cells(row: 1, column: 0)" /> <!-- '.' because row 1 is '..#' and column 0 is its first character -->
$garden = ```text
#.#
..#
```

$plot = $garden->grid()
echo $plot->cells(row: 0)              // ['#', '.', '#'] because row 0 is the top line
echo $plot->cells(column: -1)          // ['#', '#'] because -1 is the last column, and both lines end in #
echo $plot->cells(row: 1, column: 0)   // '.' because row 1 is '..#' and column 0 is its first character

As linhas podem ter tamanhos diferentes, como em um mapa irregular. Uma coluna então pula as linhas curtas demais para alcançá-la, e nada é inventado para preencher a lacuna:

<let name="steps">```text
    #.#
    #
    ```</let>

<echo value="$steps->grid()->cells(columns)" />
<!-- [['#', '#'], ['.'], ['#']] because the second line only reaches column 0 -->
$steps = ```text
#.#
#
```

echo $steps->grid()->cells(columns)
// [['#', '#'], ['.'], ['#']] because the second line only reaches column 0

->cells() funciona em qualquer lista de listas, não só em uma grade: [[1, 2], [3, 4]]->cells(columns) é [[1, 3], [2, 4]], que transforma linhas em colunas.

Encontrando coisas em uma grade: positions_of

->positions_of(item) devolve todos os lugares em que um item aparece em uma grade, como pontos com .row e .column, linha por linha e da esquerda para a direita. Dada uma função, devolve os lugares onde a função é verdadeira para a célula:

<let name="garden">```text
    #.#
    ..#
    ```</let>

<let name="trees" value="$garden->grid()->positions_of('#')" />
<!-- [{ 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 there is a # at row 1, column 2 -->
<echo value="$trees->contains({ row: 1, column: 0 })" /> <!-- false because row 1 starts with a . -->
$garden = ```text
#.#
..#
```

$trees = $garden->grid()->positions_of('#')
// [{ 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 there is a # at row 1, column 2
echo $trees->contains({ row: 1, column: 0 })   // false because row 1 starts with a .

Pontos funcionam bem com ->combinations(2), que devolve cada par uma vez, com o ponto anterior primeiro. Uma função com dois parâmetros recebe os dois pontos do par um a um. Isto conta os quadrados cujos quatro cantos são todos árvores, mesmo com outras árvores entre os cantos:

<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

Encontrar formas: shapes

->shapes() encontra formas em texto, uma lista, uma grade ou uma lista 3D: quadrados, retângulos, linhas e círculos que já vêm embutidos, e máscaras, que são formas que você desenha. O texto é lido da mesma forma que ->grid() o lê, uma linha por linha e uma célula por caractere, então não é preciso chamar ->grid() antes. As células de uma grade podem conter qualquer coisa, então, para as formas embutidas, of: diz quais células formam a forma: um valor, como '#', ou uma regex, como /[#@]/. Cada correspondência é retornada uma vez, como { kind, points }, e cada ponto é uma célula { row, column, value }. Outras células podem ficar entre os pontos de uma forma:

<let name="field">```text
    #.##.
    .....
    .#...
    ##.##
    ```</let>

<echo value="$field->shapes(square, of: '#')->count()" />
<!-- 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them -->
$field = ```text
#.##.
.....
.#...
##.##
```

echo $field->shapes(square, of: '#')->count()
// 1 because the #s at columns 0 and 3 of row 0 have #s 3 rows below both of them

Sem rotated, as formas ficam retas: quadrados e retângulos têm lados paralelos aos eixos, e as linhas vão na horizontal ou na vertical. Com rotated, elas podem ficar inclinadas, então um quadrado pode virar um losango e uma linha pode seguir na diagonal:

<let name="kite">```text
    ..#..
    .#.#.
    ..#..
    ```</let>

<echo value="$kite->shapes(square, of: '#')->count()" /> <!-- 0 because no four #s make a square with level sides -->
<echo value="$kite->shapes(square, of: '#', rotated)->count()" /> <!-- 1 because the four #s make a diamond, a square on its corner -->
$kite = ```text
..#..
.#.#.
..#..
```

echo $kite->shapes(square, of: '#')->count()            // 0 because no four #s make a square with level sides
echo $kite->shapes(square, of: '#', rotated)->count()   // 1 because the four #s make a diamond, a square on its corner

Informe várias formas para encontrá-las todas. Uma correspondência é retornada apenas uma vez, mesmo que se encaixe em mais de uma forma: um quadrado também é um retângulo, então ele volta como quadrado, e .kind indica qual é:

<let name="plot">```text
    @@@.
    @..@
    @@@@
    ```</let>

<echo value="$plot->shapes(rectangle, of: '@')->count()" /> <!-- 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2 -->
<echo value="$plot->shapes(square, rectangle, of: '@')->map(.kind)" />
<!-- ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well -->

<echo value="$plot->shapes(line, of: '@', size: 4)->count()" /> <!-- 1 because only the bottom row has 4 @s in a row -->
<echo value="$plot->shapes(line, of: '@', size: 3, rotated)->count()" /> <!-- 4 because rotated lets lines run diagonally too -->
$plot = ```text
@@@.
@..@
@@@@
```

echo $plot->shapes(rectangle, of: '@')->count()                 // 4 because three rectangles share rows 0 and 2, and one shares rows 1 and 2
echo $plot->shapes(square, rectangle, of: '@')->map(.kind)
// ['square', 'rectangle', 'rectangle', 'rectangle'] because the 2 by 2 one is a square, so it isn't a rectangle as well

echo $plot->shapes(line, of: '@', size: 4)->count()             // 1 because only the bottom row has 4 @s in a row
echo $plot->shapes(line, of: '@', size: 3, rotated)->count()    // 4 because rotated lets lines run diagonally too

Uma linha precisa de size:, o número de pontos que ela tem. Um círculo precisa de radius:, e distance: define o que é distância: straight (em linha reta, o padrão), steps (apenas horizontal e vertical, o que desenha um losango) ou moves (diagonais contam como um passo, o que desenha um anel quadrado):

<let name="pond">```text
    .~.
    ~.~
    .~.
    ```</let>

<echo value="$pond->shapes(circle, of: '~', radius: 1)->count()" /> <!-- 1 because the four ~s are each 1 away from the middle -->
<echo value="$pond->shapes(circle, of: '~', radius: 1, distance: moves)->count()" /> <!-- 0 because with moves the corners are 1 away too, and they aren't ~ -->
$pond = ```text
.~.
~.~
.~.
```

echo $pond->shapes(circle, of: '~', radius: 1)->count()                   // 1 because the four ~s are each 1 away from the middle
echo $pond->shapes(circle, of: '~', radius: 1, distance: moves)->count()  // 0 because with moves the corners are 1 away too, and they aren't ~

->shapes() também funciona com uma lista de pontos, como as que ->positions_of() gera ou as linhas lidas de um csv. Nesse caso, todos os pontos contam, então não há of:: $trees->shapes(square, rotated).

Formas próprias: máscaras

A mask is a shape you draw. Built-in shapes only know where the points are; a mask says exactly what every cell must hold, gaps included. Declare it as a type that extends Mask, and draw it in its layout: a text block that pictures the shape, one character a cell. Every character matches a cell that holds the same character. The indentation every line shares isn't part of the picture, so indent it with the code around it.

Para encontrar um bloco sólido de 2 por 2 de #s, desenhe-o e passe a máscara para ->shapes() pelo nome:

<type name="Block" description="Four #s packed into a square." extends="Mask">
  <field name="layout" default="```text
      ##
      ##
      ```" />
</type>

<let name="roof">```text
    ###.
    ###.
    ...#
    ```</let>

<let name="blocks" value="$roof->shapes(Block)" /> <!-- the matches, top left first -->
<echo value="$blocks->count()" /> <!-- 2 because the block fits at columns 0-1 and again at columns 1-2 -->
<echo value="$blocks->first().kind" /> <!-- 'Block' because a mask's match is named after its type -->
<echo value="$blocks->first().points->map(.column)" /> <!-- [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1 -->
/// Four #s packed into a square.
type Block extends Mask {
  layout: ```text
    ##
    ##
    ```
}

$roof = ```text
###.
###.
...#
```

$blocks = $roof->shapes(Block)                   // the matches, top left first
echo $blocks->count()                            // 2 because the block fits at columns 0-1 and again at columns 1-2
echo $blocks->first().kind                       // 'Block' because a mask's match is named after its type
echo $blocks->first().points->map(.column)       // [0, 1, 0, 1] because the first block covers columns 0 and 1 of rows 0 and 1

symbols is only for the characters that mean something other than themselves. It maps a character to what it matches: a value (t: 'taken') matches a cell that holds it, a regex (/[#@]/) a cell whose text fits, a fn(cell) a cell it gives true for, and any a cell that isn't part of the shape. An any cell can hold anything, can hang over the edge of the input, and is left out of the match's points. To find four trees at the corners of a three-by-three square, with anything between them:

<type name="Corners" description="Trees at the four corners of a 3x3 square, anything between." extends="Mask">
  <field name="layout" default="```text
      #.#
      ...
      #.#
      ```" />
  <field name="symbols" default="{ '.': any }" />
</type>

<let name="orchard">```text
    #.#.#
    .#...
    #.#.#
    ```</let>

<echo value="$orchard->shapes(Corners)->count()" /> <!-- 2 because the corners fit at columns 0-2 and at columns 2-4 -->
<echo value="$orchard->shapes(Corners)->first().points->map(.symbol)" />
<!-- ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle -->
/// Trees at the four corners of a 3x3 square, anything between.
type Corners extends Mask {
  layout: ```text
    #.#
    ...
    #.#
    ```
  symbols: { '.': any }
}

$orchard = ```text
#.#.#
.#...
#.#.#
```

echo $orchard->shapes(Corners)->count()                         // 2 because the corners fit at columns 0-2 and at columns 2-4
echo $orchard->shapes(Corners)->first().points->map(.symbol)
// ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle

symbols se justifica quando as células não são caracteres únicos. Uma fileira de assentos é uma lista de palavras, e uma lista de valores é uma linha só, então o layout precisa de uma letra para cada palavra:

<type name="QuietPair" description="Two free seats side by side, with a taken seat on each side." extends="Mask">
  <field name="layout" default="```text
      tfft
      ```" />
  <field name="symbols" default="{ t: 'taken', f: 'free' }" />
</type>

<let name="row" value="['free', 'taken', 'free', 'free', 'taken', 'taken']" />
<echo value="$row->shapes(QuietPair)->count()" /> <!-- 1 because only seats 1 to 4 read taken, free, free, taken -->
/// Two free seats side by side, with a taken seat on each side.
type QuietPair extends Mask {
  layout: ```text
    tfft
    ```
  symbols: { t: 'taken', f: 'free' }
}

$row = ['free', 'taken', 'free', 'free', 'taken', 'taken']
echo $row->shapes(QuietPair)->count()   // 1 because only seats 1 to 4 read taken, free, free, taken

->shapes() aceita uma máscara ou uma lista delas, e rotated gira cada uma em todas as posições que a entrada permite: de trás para frente em uma linha, um quarto, meia volta e três quartos em uma grade, e todas as 24 orientações em 3D. As correspondências de várias máscaras voltam juntas, cada uma identificada pelo seu .kind, e máscaras e formas embutidas podem ser buscadas em uma mesma chamada:

<type name="Fork" description="Three trees in a V, with anything between them." extends="Mask">
  <field name="layout" default="```text
      t~t
      ~t~
      ```" />
  <field name="symbols" default="{ t: /[#@]/, '~': any }" />
</type>

<type name="Gap" description="Two trees with a clearing between them." extends="Mask">
  <field name="layout" default="```text
      #.#
      ```" />
</type>

<let name="wood">```text
    #.@
    .#.
    #.#
    ```</let>

<echo value="$wood->shapes(Fork)->count()" /> <!-- 1 because the V fits only with its point at the bottom -->
<echo value="$wood->shapes(Fork, rotated)->count()" /> <!-- 4 because turned a quarter, a half and three quarters, it fits once each way -->
<echo value="$wood->shapes([Fork, Gap], rotated)->map(.kind)" />
<!-- ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.# -->
<echo value="$wood->shapes(Fork)->first().points->map(.symbol)" />
<!-- ['t', 't', 't'] because ~ is any, so its cells aren't part of the match -->
/// Three trees in a V, with anything between them.
type Fork extends Mask {
  layout: ```text
    t~t
    ~t~
    ```
  symbols: { t: /[#@]/, '~': any }
}

/// Two trees with a clearing between them.
type Gap extends Mask {
  layout: ```text
    #.#
    ```
}

$wood = ```text
#.@
.#.
#.#
```

echo $wood->shapes(Fork)->count()           // 1 because the V fits only with its point at the bottom
echo $wood->shapes(Fork, rotated)->count()  // 4 because turned a quarter, a half and three quarters, it fits once each way
echo $wood->shapes([Fork, Gap], rotated)->map(.kind)
// ['Fork', 'Fork', 'Fork', 'Fork', 'Gap', 'Gap'] because the bottom row and the left column are each #.#
echo $wood->shapes(Fork)->first().points->map(.symbol)
// ['t', 't', 't'] because ~ is any, so its cells aren't part of the match

Os símbolos de uma máscara podem ser alterados onde ela é usada, como qualquer campo: Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) é o mesmo V de qualquer coisa, exceto ..

Uma linha em branco no layout começa a próxima camada, a camada de cima primeiro, assim como uma linha em branco no texto em que a máscara procura. Todas as camadas têm o mesmo número de linhas, e cada ponto de uma correspondência em 3D também tem um layer. Uma lista 3D ($cube[layer][row][column]) é lida da mesma forma:

<type name="Step" description="A step: one block on the top layer, with two under it on the layer below." extends="Mask">
  <field name="layout" default="```text
      #.

      ##
      ```" />
  <field name="symbols" default="{ '.': any }" />
</type>

<let name="tower">```text
    #..
    ...

    ##.
    .#.
    ```</let>

<echo value="$tower->shapes(Step)->count()" /> <!-- 1 because the one block on the top layer has a block under it, and another beside that -->
<echo value="$tower->shapes(Step)->first().points->map(.layer)" /> <!-- [0, 1, 1] because one point is on the top layer and two are on the layer below -->
/// A step: one block on the top layer, with two under it on the layer below.
type Step extends Mask {
  layout: ```text
    #.

    ##
    ```
  symbols: { '.': any }
}

$tower = ```text
#..
...

##.
.#.
```

echo $tower->shapes(Step)->count()                        // 1 because the one block on the top layer has a block under it, and another beside that
echo $tower->shapes(Step)->first().points->map(.layer)    // [0, 1, 1] because one point is on the top layer and two are on the layer below

Uma máscara com menos camadas ou linhas que a entrada desliza por toda ela: uma máscara de uma linha é testada em cada linha de uma grade, e uma máscara plana em cada camada de um texto 3D ou de uma lista 3D. Uma máscara com mais camadas ou linhas gera um erro que diz isso, como "Step has 2 layers, and this is one grid."

Mask é um tipo que você pode escrever para um parâmetro ou um campo. Ele aceita qualquer tipo que estenda Mask, seja o próprio tipo (Block) ou um criado a partir dele (Block(symbols: ...)), e Mask[] aceita uma lista deles:

<type name="Block" description="Four #s packed into a square." extends="Mask">
  <field name="layout" default="```text
      ##
      ##
      ```" />
</type>

<fn name="count_in" params="input: string, shape: Mask" returns="int" value="$input->shapes($shape)->count()" />
<fn name="count_all" params="input: string, shapes: Mask[]" returns="int" value="$input->shapes($shapes)->count()" />

<let name="roof">```text
    ###.
    ###.
    ...#
    ```</let>

<echo value="@count_in($roof, Block)" /> <!-- 2 because Block fits twice in the roof -->
<echo value="@count_in($roof, Block(symbols: { '#': /[#.]/ }))" /> <!-- 6 because now a . counts as well, so every 2x2 window fits -->
<echo value="@count_all($roof, [Block, Block(symbols: { '#': '.' })])" /> <!-- 2 because no 2x2 of the roof is all .s, so only Block's 2 count -->
/// Four #s packed into a square.
type Block extends Mask {
  layout: ```text
    ##
    ##
    ```
}

fn count_in(input: string, shape: Mask): int => $input->shapes($shape)->count()
fn count_all(input: string, shapes: Mask[]): int => $input->shapes($shapes)->count()

$roof = ```text
###.
###.
...#
```

echo @count_in($roof, Block)                                 // 2 because Block fits twice in the roof
echo @count_in($roof, Block(symbols: { '#': /[#.]/ }))      // 6 because now a . counts as well, so every 2x2 window fits
echo @count_all($roof, [Block, Block(symbols: { '#': '.' })]) // 2 because no 2x2 of the roof is all .s, so only Block's 2 count

A mask holds layout, symbols and its own methods, written with :. The editor and kscript check report a mask written wrong, most with a fix: a missing or empty layout, a layout that is all any, a tab in the picture, layers of different heights, a symbol that is more than one character or is listed twice, null for any, layout = for layout:, and like:, which ->shapes() no longer takes. A symbol the layout doesn't use is a warning (KS6026), and so is one that maps a character to itself (KS6025), since every character already matches itself:

<type name="Block" extends="Mask">
  <field name="layout" default="```text
      ##
      ```" />
  <field name="symbols" default="{ '#': '#' }" /> <!-- the warning: '#' already matches '#'. -->
</type>
type Block extends Mask {
  layout: ```text
    ##
    ```
  symbols: { '#': '#' }    // the warning: '#' already matches '#'.
}

In the editor, a mask is part of the language. extends ‸ offers Mask, and inside a Mask type, typing layout writes the text block; once it has one, symbols comes written out with a character of the layout and any. Inside symbols: { }, completion offers the layout's characters not yet listed. Hovering a character of the layout says what it matches and how often the layout uses it, and each character is coloured by what it matches: itself or a value like text, a regex like a regex, a fn like a function, and any dimmed like a comment.

Trabalhando com sequências

Multiplicando: product

->product(fn?) multiplica os itens, assim como ->sum() os soma. Dada uma função, ele multiplica o que a função retorna para cada item. 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, height: 5 }, { width: 3, height: 1 }]" />
<echo value="$boxes->product(fn(box) => $box.width)" /> <!-- 6 because 2 * 3 is 6 -->
<echo value="[942, 945, 571]->product()" /> <!-- 508298490 -->
echo [2, 3, 4]->product()                              // 24 because 2 * 3 * 4 is 24
$boxes = [{ width: 2, height: 5 }, { width: 3, height: 1 }]
echo $boxes->product(fn(box) => $box.width)            // 6 because 2 * 3 is 6
echo [942, 945, 571]->product()                        // 508298490

Somas acumuladas: scan

->scan(fn(total, item), initial?) funciona como ->reduce(), mas guarda cada total parcial pelo caminho, para você ver como o resultado se forma. Sem initial, o primeiro item é o primeiro total:

<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 the budget starts at 20 and each amount comes off it -->
$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 the budget starts at 20 and each amount comes off it

Todas as escolhas: combinations

->combinations(size) fornece todas as formas de escolher size itens da lista 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.

Escolher 2 de ['tea', 'milk', 'juice'] funciona assim: comece com tea e combine-o com cada item depois dele (milk, depois juice), depois comece com milk e combine-o com cada item depois dele (juice). juice não tem nada depois, então não há mais nada. ['milk', 'tea'] nunca aparece, porque é 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(1)" />
<!-- [['tea'], ['milk'], ['juice']] -->
$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(1)
// [['tea'], ['milk'], ['juice']]

Um uso comum é verificar todos os pares, por exemplo para 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)" />
<!-- [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)
// [40, 25] because 15 + 40, 15 + 25 and 15 + 60 aren't 65, but 40 + 25 is

Uma função com um parâmetro para cada item escolhido recebe os itens um a um, para que você possa dar nome a eles em vez de ler $two[0] e $two[1]. Isso funciona para qualquer tamanho: escolhas de 3 preenchem fn(first, second, third). Uma função com um único parâmetro ainda recebe a escolha inteira:

<let name="prices" value="[15, 40, 25, 60]" />
<echo value="$prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)" />
<!-- 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is -->

<let name="sides" value="[3, 4, 5, 9]" />
<echo value="$sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)" />
<!-- 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25 -->

<echo value="$sides->combinations(3)->map(fn(three) => $three->sum())" />
<!-- [12, 16, 17, 18] because a function with one parameter gets each pick as a list -->
$prices = [15, 40, 25, 60]
echo $prices->combinations(2)->count_of(fn(cheaper, dearer) => $cheaper + $dearer > 70)
// 3 because 15 + 60, 40 + 60 and 25 + 60 are over 70, and no other pair is

$sides = [3, 4, 5, 9]
echo $sides->combinations(3)->count_of(fn(shortest, middle, longest) => $shortest ** 2 + $middle ** 2 == $longest ** 2)
// 1 because only 3, 4 and 5 make a right-angled triangle: 9 + 16 is 25

echo $sides->combinations(3)->map(fn(three) => $three->sum())
// [12, 16, 17, 18] because a function with one parameter gets each pick as a list

Como os itens escolhidos preenchem os parâmetros, essa função não recebe também o índice: com pares, fn(first, second) são os dois itens do par.

Toda ordem: permutações

->permutations(size?) fornece todas as ordenações, em que a ordem importa, então ['tea', 'milk'] e ['milk', 'tea'] estão ambas lá. Sem size, cada ordenação usa todos os itens:

<echo value="['tea', 'milk', 'juice']->permutations()" />
<!--
  6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
  because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6
-->

<echo value="['tea', 'milk', 'juice']->permutations(2)->count()" />
<!-- 6 because 3 choices for first and 2 for second -->
echo ['tea', 'milk', 'juice']->permutations()
// 6 orderings: [['tea', 'milk', 'juice'], ['tea', 'juice', 'milk'], ['milk', 'tea', 'juice'], ...]
// because there are 3 choices for first, 2 for second and 1 for third, and 3 * 2 * 1 is 6

echo ['tea', 'milk', 'juice']->permutations(2)->count()
// 6 because 3 choices for first and 2 for second

Combinações e permutações crescem rápido (10 itens têm 3.628.800 ordenações), então, passando de um milhão de listas, elas param com um erro Limit em vez de esgotar a memória.

Dando a volta: rotate

->rotate(by) move cada item by posições para o início, e os que caem pela frente vão para o fim. Um by negativo faz o movimento no sentido contrário:

<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 -->
$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

Adicionando métodos a um tipo: extend

extend adiciona seus próprios métodos a um tipo, embutido ou seu. Dentro dele, cada fn é um método, e $this é o valor sobre o qual ele é chamado:

<extend type="date">
  <fn name="api_date" description="The date as text for an API: 2026-11-21." value="$this->format('yyyy-MM-dd')" />
  <fn name="is_payday" value="$this.day == 25" />
</extend>

<extend type="list">
  <fn name="second" value="$this[1]" />
</extend>

<extend type="string">
  <fn name="slug" value="$this->lower()->trim()->replace(' ', '-')" />
</extend>

<echo>{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }</echo>
<echo>{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }</echo>
extend date {
  /// The date as text for an API: 2026-11-21.
  fn api_date() => $this->format('yyyy-MM-dd')
  fn is_payday() => $this.day == 25
}

extend list {
  fn second() => $this[1]
}

extend string {
  fn slug() => $this->lower()->trim()->replace(' ', '-')
}

echo "{ '2026-11-25'->to_date()->api_date() } { '2026-11-25'->to_date()->is_payday() }"
echo "{ ['a', 'b', 'c']->second() } { 'Hello World'->slug() } { 'Hello World' |> slug() }"

You can extend string, number (or int and float), bool, list, map, fn, date, email, password, handle, uuid and regex, a package's values such as file or response, and your own types, whose methods see $this (a record) and its fields as $this.name. Methods take parameters, defaults and named arguments like any fn.

Um método não pode receber o nome de um que o tipo já tem, então um erro de digitação ou um conflito nunca muda o que um método embutido faz. Para substituir um de propósito, escreva override:

<extend type="date">
  <fn name="to_string" override="yes" value="$this->format('d MMMM yyyy')" />
</extend>
extend date {
  override fn to_string() => $this->format('d MMMM yyyy')
}

Em XML, extend é <extend type="date"> contendo elementos <fn>, e override fn é <fn override="true">.

Onde as extensões se aplicam. Os blocos extend de um arquivo se aplicam nesse arquivo e em todo arquivo que o importe. Em um projeto (uma pasta com kscript.json), todo arquivo da pasta extensions/ se aplica a todo script, teste e página do projeto, sem precisar de import. Separe-os como quiser, por exemplo um arquivo por tipo:

Texto
extensions/
  date.kscript        extend date { … }
  list.kscript        extend list { … }
  text/
    slug.kscript      extend string { … }

kscript make extension date --methods api_date,is_payday cria extensions/date.kscript como ponto de partida. Para guardá-los em outro lugar, liste pastas ou globs em kscript.json, o que substitui a pasta padrão: "extensions": ["extensions", "shared/**/*.kscript"]. Dois arquivos de extensão que adicionam o mesmo método ao mesmo tipo é um erro, e a mensagem nomeia os dois. A extend própria de um script (ou de um import) prevalece sobre a do projeto.

O editor completa e verifica métodos de extensão somente onde eles se aplicam: em um arquivo que não declara, não importa e (por meio do projeto) não recebe ->api_date() em datas, @today()->api_date() continua sendo um método desconhecido. Ao passar o mouse, aparece a documentação /// do método e o arquivo que o adiciona, e ir para a definição abre esse arquivo.

Edit this page on GitHub