KScript documentazione
IT

Lingua

Tradotto automaticamente dall’inglese, che è la versione originale.

Il linguaggio

Valori e metodi

I valori sono stringhe, numeri, bool, liste, mappe, date, funzioni e null, più i valori che aggiungono i pacchetti (file, risposte HTTP). Ogni valore ha dei metodi, richiamati con -> e concatenabili:

<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') }"

Usa pluck(key) per leggere un campo da ogni elemento in ordine. Passa a pluck una lista di chiavi per produrre una nuova mappa per ogni elemento. Le chiavi possono essere nomi semplici, stringhe tra virgolette o variabili.

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

Una chiave di mappa mancante dà null. I record tipizzati mantengono i consueti controlli sui campi. Una lista di input vuota dà [], e pluck([]) dà una mappa vuota per ogni elemento di input. Le chiavi ripetute compaiono una sola volta, nell'ordine richiesto.

Su una lista, contains(value), index_of(value), remove(value) e count_of(value) confrontano con ==. Per esempio, [1, '1']->count_of(1) dà 2. unique() usa l'uguaglianza stretta (===), quindi [1, '1']->unique() mantiene entrambi gli elementi.

is_empty() significa zero caratteri su una stringa, zero elementi su una lista, o zero chiavi su una mappa. Se hai usato $text->is_empty() per accettare input composto solo da spazi, usa $text->is_blank() per mantenere quel comportamento.

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

Un numero è sempre scritto in cifre semplici, mai con un esponente: echo 10 ** 20 stampa 100000000000000000000 e echo 0.1 ** 20 stampa 0.00000000000000000001. I numeri interi sono esatti a qualsiasi dimensione: 123456789 * 987654321 è 121932631112635269, 2 ** 100 è 1267650600228229401496703205376, e un id di 20 cifre letto da testo o JSON mantiene tutte le cifre. +, -, *, %, **, / (quando divide esattamente), ->sum(), ->product(), @gcd, @lcm e @factorial restano tutti esatti; una frazione, @sqrt e simili funzionano in normale virgola mobile. Una frazione mostra 15 cifre significative, quindi 0.1 + 0.2 stampa 0.3. Un numero intero può crescere fino a circa 30.000 cifre prima di fermarsi con un errore di Limit.

Sul testo, ->count() e le posizioni (in ->slice(), ->index_of() e $text[0]) contano la maggior parte dei caratteri come un posto e un carattere come un'emoji come due. Nessun metodo spezza a metà un carattere del genere: ->chars(), ->first(), ->last() e ->reverse() lavorano con i caratteri interi come li vede chi legge, e ->slice() e ->truncate() spostano indietro, fino a prima di esso, un taglio che cadrebbe al suo interno.

Un semplice fatto su un valore è un campo, letto con un punto e senza parentesi, allo stesso modo delle chiavi di una mappa:

<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 }"

Quindi $response.status, $file.size, $url.host e $e.status sono campi, e tutto ciò che accetta argomenti o esegue un'operazione è un metodo: $response->convert(from: json), $file->read_text(), $day->format('yyyy'). Un nome che risponde true o false inizia con is_ o has_: $response.is_ok, $ip.is_private, $list->is_empty(), $map->has(key).

Una durata è un numero e un'unità senza virgolette, come 500ms, 30s, 10m, 2h, 1d o 1w, uniti per indicarne di più (1h30m). Tutto ciò che accetta una durata ne richiede una: wait(500ms), @api($url, options: { timeout: 30s }), $cache->set(key, value, ttl: 10m). Un numero semplice è sempre in secondi.

Anni e mesi sono y e mo (m sono i minuti): 1y, 6mo, 5y10mo. Un mese o un anno non ha una lunghezza fissa, quindi questi spostano le date secondo il calendario ($date + 1mo mantiene il giorno del mese dove possibile) e vengono rifiutati dove serve una lunghezza fissa, come wait(1mo) o 1mo.hours.

L'editor completa i campi e i metodi di ogni tipo e mostra cosa fanno. Per cambiare il formato di un valore, come leggere testo JSON o scrivere righe come CSV, usa ->convert(): vedi Conversione tra formati.

Date

I fatti di calendario di una data sono campi: .year, .month, .day, .weekday, .quarter, .day_of_year, .week (il numero di settimana ISO) e .days_in_month. .is_past, .is_future, .is_today e .is_weekend la confrontano con adesso, quindi sono adatti ai template:

<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) danno il primo e l'ultimo istante del day, week, month, quarter o year in cui cade una data, che è ciò che serve a un report sugli "ordini di questo mese". Una settimana inizia nel primo giorno della localizzazione (lunedì in en-GB, domenica in en-US), oppure in quello indicato da week_start::

<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

L'aritmetica di calendario conta unità intere. $date + 1y6mo sposta una data di anni e mesi, e così fa ->add(), che accetta qualsiasi combinazione di years:, months:, weeks: e days: (->subtract() la sposta indietro). Un mese mantiene il giorno del mese dove possibile, quindi il 31 gennaio più un mese è l'ultimo giorno di febbraio. Per ore e minuti, aggiungi o togli una durata:

<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

Una data si sposta solo di una durata. $date + 1 è un errore, perché un numero semplice è sempre in secondi, e così lo è aggiungere un bool, una lista o un'altra data. Scrivi l'unità ($date + 3d). L'unico caso in cui un numero rappresenta una data è un timestamp Unix, i secondi dal 1970, che ->to_date() legge e ->timestamp() restituisce:

<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

Sottrarre una data da un'altra dà il tempo esatto tra le due come durata. ->since(other, in: unit) conta invece giorni, settimane, mesi o anni interi, come si fa per un compleanno. ->is_same(other, unit) chiede se due date cadono nello stesso giorno (il valore predefinito), settimana, mese, trimestre o anno:

<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 deriva dall'orologio del computer, quindi nei test @with_clock(date, fn) lo fissa per @now(), @today(), i campi sopra e @format_relative().

Lavorare con il testo

Il testo ha funzioni di supporto per le operazioni che ricorrono spesso: cambiare il maiuscolo/minuscolo di un nome, tagliare in corrispondenza di un separatore, sistemare gli spazi e firmare un 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() tagliano al primo separatore, o all'ultimo con last, e restituiscono l'intero testo quando il separatore non c'è. ->wrap(width: 60) spezza il testo tra le parole in modo che stia in una larghezza, come @terminal_width(). ->is_numeric() è vero per testi come '42' o '-3.5'.

->contains(), ->starts_with(), ->ends_with(), ->index_of() (l'ultima corrispondenza con last) e ->replace() corrispondono esattamente alle maiuscole e alle minuscole. Passa ignore_case per far corrispondere maiuscole e minuscole allo stesso modo:

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

Per verificare un webhook, calcola la firma con ->hmac(key) (SHA-256 di default, oppure sha1 o sha512) e confrontala con @secure_equals(), che richiede lo stesso tempo indipendentemente da quanto i due valori coincidono:

<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() restituiscono hash in esadecimale. @escape_regex(text) esegue l'escape di ciò che un utente ha digitato, così un pattern costruito con quel testo corrisponde solo a quel testo.

Liste e mappe

Le liste si confrontano come insiemi con ->difference(other), ->intersect(other) e ->union(other). Ognuna mantiene l'ordine della prima lista, restituisce ogni elemento una sola volta e confronta gli elementi con ==, oppure con ciò che by: restituisce per ciascuno:

<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 gli elementi per ogni chiave, ->take_while(fn) e ->skip_while(fn) si fermano al primo elemento che non soddisfa la condizione, ->window(size, step?) restituisce sequenze sovrapposte e ->replace_at(index, item) restituisce una copia con un elemento modificato:

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

Più e meno frequenti: common

->common(count?, least, by?) conta quante volte compare ogni elemento e restituisce gli elementi in quell'ordine, una sola volta ciascuno. Senza least compaiono prima i più frequenti; con least compaiono prima i più rari. count tiene solo quel numero di elementi dall'inizio e, se lo ometti, ottieni tutti gli elementi distinti. Gli elementi che compaiono con la stessa frequenza restano nell'ordine in cui compaiono per la prima volta nella lista, e ogni elemento torna com'è, quindi i numeri restano numeri:

<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 cosa conta come lo stesso elemento. Qui 'Tea' e 'tea' vengono contati insieme perché entrambi diventano 'tea' in minuscolo, e ottieni indietro quello che è comparso per primo:

<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

Per moltiplicare tra loro i tre numeri più frequenti, prendili con ->common(3) e moltiplicali con ->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

Le mappe hanno gli stessi callback delle liste, che ricevono prima il valore e poi la chiave: ->filter(), ->reject(), ->any(), ->all(), ->find() (che restituisce { key, value }), ->reduce(), ->sort(by:) e ->map(). ->map_keys(fn) rinomina ogni chiave, ricevendo prima la chiave e poi il valore:

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

Conversione tra formati: convert

I dati passano continuamente da un formato all'altro: un'API risponde in JSON, un file di impostazioni è in YAML, un foglio di calcolo viene salvato come CSV. Ogni valore ha un unico metodo per tutto questo, ->convert(), e si legge come una frase: converti da questo formato, a quell'altro.

from: legge un testo scritto in un formato e ti restituisce i valori che contiene. to: scrive un valore in un formato. Passa entrambi per trasformare direttamente un formato in un altro.

Formato from: lo legge to: lo scrive
json mappe, liste, testi, numeri testo json
yaml mappe, liste, testi, numeri testo yaml
csv una lista di righe testo csv
markdown, latex un documento con KScript.Document
html da Markdown con KScript.Markdown, da documenti con KScript.Document

Lettura di un testo: from

from: accetta un testo, un blocco di testo come un blocco ```yaml o ```csv, un valore json o csv, oppure una risposta HTTP (il suo 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

Il CSV ha di default una riga di intestazione, che dà il nome alle chiavi di ogni riga. Scrivi not header quando ogni riga è un dato, e ogni riga diventa una lista delle sue celle:

<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

Controllo rispetto a un tipo: as

as: verifica ciò che è stato letto rispetto a un tipo e lo trasforma in record, così un campo mancante o errato diventa un errore sulla riga che lo legge, non una sorpresa più avanti. Una lista di record si scrive come la scrive una dichiarazione, 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

Scrittura di un formato: to

to: scrive qualsiasi valore: mappe e liste come JSON o YAML, e una lista di righe come CSV. indented distribuisce il JSON su più righe, e headers: sceglie e ordina le colonne del 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

Entrambi insieme

Passa from: e to: insieme per convertire un formato in un altro senza gestire i valori nel mezzo:

<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

Scorciatoie: from e to

Quando ti limiti a leggere o solo a scrivere, ->from(type: json) e ->to(type: csv) dicono la stessa cosa con meno parole. Accettano le stesse opzioni di ->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() è l'unico modo per cambiare formato, quindi le vecchie forme con un metodo per formato (->json(), ->yaml(), ->csv(), ->markdown(), ->to_json(), ->to_yaml(), ->to_csv(), e ->html(), ->latex() e ->markdown() di un documento) sono errori che mostrano invece la ->convert() da scrivere, con una correzione nell'editor.

Lettura di testo strutturato

I dati spesso arrivano come testo: un record per riga, gruppi di righe separati da una riga vuota, oppure un disegno fatto di caratteri. Questi metodi trasformano quel testo in liste con cui puoi lavorare.

Righe e blocchi

->lines() restituisce un testo per ogni riga. ->blocks() invece divide il testo nelle righe vuote, così ogni blocco è un gruppo di righe. Un semplice a capo resta dentro il blocco; solo una riga vuota ne inizia uno nuovo:

<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() al posto di una funzione è una scorciatoia per fn(block) => $block->lines(): il metodo viene chiamato su ogni elemento, come .name legge il campo di ogni elemento. Funziona ovunque serva una funzione, ad esempio in ->filter(.is_empty()) o ->sort(by: .age).

Divisione di una lista: split

Quando hai già una lista, ->split(separator) la taglia in più liste ogni volta che compare l'elemento separatore, e lo scarta. Passa un valore da cercare con ==, oppure una condizione vera per il separatore:

<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() su un testo taglia il testo; ->split() su una lista taglia la lista.

Numeri nel testo: numbers

->numbers() restituisce tutti i numeri scritti nel testo, in ordine, così non ti serve un pattern. Un segno meno conta come segno quando si trova subito prima di un numero senza nulla attaccato alla sua sinistra, come in x=-3; tra due numeri, come in 1-3, è un trattino, quindi ottieni 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]

Disegni fatti di caratteri: grid

->grid() trasforma le righe di caratteri in righe di singoli caratteri, quindi $grid[row][column] è un carattere. La riga 0 è quella in alto e la colonna 0 è il primo carattere:

<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

Scorrere righe e colonne: cells

->cells() legge una griglia come si leggerebbe una tabella. Da solo, o con rows, restituisce ogni riga; con columns restituisce ogni colonna, dall'alto in basso. È così che si scorre una griglia in entrambe le direzioni:

<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: sceglie una riga e column: una colonna, entrambe numerate da 0, e -1 è l'ultima. Passa entrambe per ottenere l'unica cella in cui si incontrano:

<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

Le righe possono avere lunghezze diverse, come in una mappa irregolare. Una colonna salta allora le righe troppo corte per arrivarci, quindi nessun valore viene inventato per riempire il vuoto:

<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() funziona su qualsiasi lista di liste, non solo su una griglia: [[1, 2], [3, 4]]->cells(columns) è [[1, 3], [2, 4]], che trasforma le righe in colonne.

Trovare elementi in una griglia: positions_of

->positions_of(item) restituisce ogni posizione in cui si trova un elemento in una griglia, come punti con una .row e una .column, riga per riga e da sinistra a destra. Se passi una funzione, restituisce le posizioni in cui la funzione è vera per la cella:

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

I punti funzionano bene con ->combinations(2), che restituisce ogni coppia una sola volta con il punto precedente per primo. Una funzione con due parametri riceve i due punti della coppia uno alla volta. Questo esempio conta i quadrati i cui quattro angoli sono tutti alberi, anche con altri alberi tra gli angoli:

<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

Ricerca di forme: shapes

->shapes() trova forme in un testo, un elenco, una griglia o un elenco 3D: quadrati, rettangoli, linee e cerchi integrati, e maschere, cioè forme che disegni tu. Il testo viene letto come lo legge ->grid(), una riga per linea e una cella per carattere, quindi non serve chiamare prima ->grid(). Le celle di una griglia possono contenere qualsiasi cosa, quindi per le forme integrate of: indica quali celle formano la forma: un valore come '#', oppure un'espressione regolare come /[#@]/. Ogni corrispondenza viene restituita una sola volta, come { kind, points }, e ogni punto è una cella { row, column, value }. Tra i punti di una forma possono trovarsi altre celle:

<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

Senza rotated, le forme sono dritte: quadrati e rettangoli hanno lati paralleli agli assi, e le linee corrono in orizzontale o in verticale. Con rotated possono essere inclinate, quindi un quadrato può diventare un rombo e una linea può correre in diagonale:

<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

Indica più forme per trovarle tutte. Una corrispondenza viene data una sola volta anche quando si adatta a più forme: un quadrato è anche un rettangolo, quindi viene restituito come quadrato, e .kind indica quale forma è:

<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

Una linea richiede size:, cioè quanti punti ha. Un cerchio richiede radius:, e distance: indica quanto è lontano: straight (in linea d'aria, il valore predefinito), steps (solo in orizzontale e verticale, che disegna un rombo) oppure moves (le diagonali contano come uno, che disegna un anello quadrato):

<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() funziona anche su un elenco di punti, come quelli che ->positions_of() restituisce o le righe lette da un csv. In quel caso ogni punto conta, quindi non c'è of:: $trees->shapes(square, rotated).

Forme personalizzate: maschere

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.

Per trovare un blocco pieno due per due di #, disegnalo e passa la maschera a ->shapes() per 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 si rivela utile quando le celle non sono singoli caratteri. Una fila di posti è una lista di parole, e una lista di valori è una riga, quindi il layout ha bisogno di una lettera per ogni parola:

<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() accetta una maschera o un elenco di maschere, e rotated le trasforma in ogni modo consentito dall'input: da destra a sinistra lungo una riga, di un quarto, di metà e di tre quarti in una griglia, e in tutti i 24 orientamenti nello spazio 3D. Le corrispondenze di più maschere vengono restituite insieme, ciascuna identificata dal proprio .kind, e maschere e forme integrate possono essere cercate in un'unica chiamata:

<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

I simboli di una maschera si possono cambiare nel punto in cui viene usata, come qualsiasi campo: Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) è la stessa V di qualsiasi cosa tranne ..

Una riga vuota nel layout inizia il livello successivo, dal livello superiore, come accade con una riga vuota nel testo in cui la maschera cerca. Ogni livello ha lo stesso numero di righe, e ogni punto di una corrispondenza in 3D ha anch'esso un layer. Un elenco 3D ($cube[layer][row][column]) viene letto allo stesso modo:

<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

Una maschera con meno livelli o righe dell'input scorre su tutto l'input: una maschera di una sola riga viene provata su ogni riga di una griglia, e una maschera piatta su ogni livello di un testo 3D o di un elenco 3D. Una maschera con più livelli o righe dà un errore che lo spiega, come "Step has 2 layers, and this is one grid."

Mask è un tipo che puoi scrivere per un parametro o un campo. Accetta qualsiasi tipo che estende Mask, sia il tipo stesso (Block) sia uno ricavato da esso (Block(symbols: ...)), e Mask[] accetta una lista di questi:

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

Lavorare con le sequenze

Moltiplicare: product

->product(fn?) moltiplica gli elementi, come ->sum() li somma. Dato una funzione, moltiplica i risultati della funzione per ogni elemento. I numeri interi restano esatti a qualsiasi dimensione:

<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

Totali parziali: scan

->scan(fn(total, item), initial?) funziona come ->reduce() ma conserva ogni totale intermedio, così vedi come si costruisce il risultato. Senza initial, il primo elemento è il primo totale:

<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

Ogni scelta: combinations

->combinations(size) fornisce ogni modo per scegliere size elementi dalla lista quando l'ordine degli elementi scelti non conta. Ogni scelta mantiene gli elementi nell'ordine della lista, e nella stessa scelta nessun elemento viene scelto due volte.

Scegliendo 2 da ['tea', 'milk', 'juice'] funziona così: parti da tea e abbinalo a ogni elemento che segue (milk, poi juice), poi parti da milk e abbinalo a ogni elemento che segue (juice). juice non ha nulla dopo di sé, quindi non c'è altro. ['milk', 'tea'] non compare mai, perché è la stessa scelta di ['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']]

Un uso comune è controllare ogni coppia, per esempio trovare i due prezzi che sommati danno un totale:

<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

Una funzione con un parametro per ogni elemento scelto riceve gli elementi uno alla volta, così puoi dare loro un nome invece di leggere $two[0] e $two[1]. Funziona per qualunque dimensione: scelte di 3 riempiono fn(first, second, third). Una funzione con un solo parametro riceve comunque l'intera scelta:

<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

Poiché gli elementi scelti riempiono i parametri, una funzione del genere non riceve anche l'indice: con le coppie, fn(first, second) sono i due elementi della coppia.

Ogni ordine: permutazioni

->permutations(size?) fornisce ogni ordinamento, in cui l'ordine conta, quindi ['tea', 'milk'] e ['milk', 'tea'] sono entrambi presenti. Senza size ogni ordinamento usa tutti gli elementi:

<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

Combinazioni e permutazioni crescono rapidamente (10 elementi hanno 3.628.800 ordinamenti), quindi oltre un milione di liste si fermano con un errore Limit invece di esaurire la memoria.

Girare: rotate

->rotate(by) sposta ogni elemento di by posizioni verso l'inizio, e quelli che cadono davanti vanno in fondo. Un by negativo gira nell'altra direzione:

<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

Aggiungere metodi a un tipo: extend

extend aggiunge i tuoi metodi a un tipo, integrato o tuo. Dentro, ogni fn è un metodo, e $this è il valore su cui viene chiamato:

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

Un metodo non può avere il nome di uno che il tipo già possiede, quindi un refuso o un conflitto non cambia mai ciò che fa un metodo integrato. Per sostituirne uno di proposito, scrivi 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')
}

In XML, extend è <extend type="date"> che contiene elementi <fn>, e override fn è <fn override="true">.

Dove si applicano le estensioni. I blocchi extend di un file si applicano in quel file e in ogni file che lo importa. In un progetto (una cartella con kscript.json), ogni file nella cartella extensions/ si applica a ogni script, test e pagina del progetto, senza bisogno di import. Dividile come preferisci, per esempio un file per tipo:

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

kscript make extension date --methods api_date,is_payday crea extensions/date.kscript come punto di partenza. Per tenerli altrove, elenca cartelle o glob in kscript.json, che sostituisce la cartella predefinita: "extensions": ["extensions", "shared/**/*.kscript"]. Due file di estensione che aggiungono lo stesso metodo allo stesso tipo sono un errore che indica entrambi. Il extend di uno script (o di un import) prevale su quello del progetto.

L'editor completa e controlla i metodi di estensione solo dove si applicano: in un file che non li dichiara, non importa e (tramite il progetto) non riceve ->api_date() sulle date, @today()->api_date() è ancora un metodo sconosciuto. Al passaggio del mouse compaiono la documentazione del metodo /// e il file che lo aggiunge, e andare alla definizione apre quel file.

Edit this page on GitHub