Valores y métodos
Los valores son cadenas, números, booleanos, listas, mapas, fechas, funciones y null, además de los valores que añaden los paquetes (archivos, respuestas HTTP). Cada valor tiene métodos, que se llaman con -> y se encadenan:
<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) para leer un campo de cada elemento en orden. Pasa a pluck una lista de claves para producir un nuevo mapa por elemento. Las claves pueden ser nombres sin comillas, cadenas entre comillas o variables.
<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 clave de mapa que falta da null. Los registros tipados mantienen sus comprobaciones de campo habituales. Una lista de entrada vacía da [], y pluck([]) da un mapa vacío por cada elemento de entrada. Las claves repetidas aparecen una sola vez, en el orden solicitado.
En una lista, contains(value), index_of(value), remove(value) y count_of(value) comparan con ==. Por ejemplo, [1, '1']->count_of(1) da 2. unique() usa igualdad estricta (===), así que [1, '1']->unique() conserva ambos elementos.
is_empty() significa cero caracteres en una cadena, cero elementos en una lista o cero claves en un mapa. Si usaste $text->is_empty() para aceptar entradas formadas solo por espacios, usa $text->is_blank() para mantener ese comportamiento.
| Texto | ->is_empty() |
->is_blank() |
|---|---|---|
'' |
true |
true |
' ' |
false |
true |
'hello' |
false |
false |
Un número siempre se escribe con dígitos simples, nunca con exponente: echo 10 ** 20 imprime 100000000000000000000 y echo 0.1 ** 20 imprime 0.00000000000000000001. Los números enteros son exactos a cualquier tamaño: 123456789 * 987654321 es 121932631112635269, 2 ** 100 es 1267650600228229401496703205376, y un id de 20 dígitos leído desde texto o JSON conserva todos los dígitos. +, -, *, %, **, / (cuando divide exactamente), ->sum(), ->product(), @gcd, @lcm y @factorial siguen siendo exactos; una fracción, @sqrt y similares funcionan en coma flotante normal. Una fracción muestra 15 dígitos significativos, así que 0.1 + 0.2 imprime 0.3. Un número entero puede crecer hasta unos 30.000 dígitos antes de detenerse con un error de Límite.
En texto, ->count() y las posiciones (en ->slice(), ->index_of() y $text[0]) cuentan la mayoría de caracteres como un lugar y un carácter como un emoji como dos. Ningún método corta ese carácter por la mitad: ->chars(), ->first(), ->last() y ->reverse() trabajan con caracteres completos tal como los ve un lector, y ->slice() y ->truncate() desplazan un corte que caería dentro de uno hasta antes de él.
Un dato simple sobre un valor es un campo, que se lee con un punto y sin corchetes, igual que se leen las claves de un 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 }"Así que $response.status, $file.size, $url.host y $e.status son campos, y todo lo que recibe argumentos o hace trabajo es un método: $response->convert(from: json), $file->read_text(), $day->format('yyyy'). Un nombre que responde verdadero o falso empieza por is_ o has_: $response.is_ok, $ip.is_private, $list->is_empty(), $map->has(key).
Una duración de tiempo es un número y una unidad sin comillas, como 500ms, 30s, 10m, 2h, 1d o 1w, que se unen para más (1h30m). Todo lo que recibe una duración de tiempo acepta una: wait(500ms), @api($url, options: { timeout: 30s }), $cache->set(key, value, ttl: 10m). Un número simple siempre son segundos.
Años y meses son y y mo (m son minutos): 1y, 6mo, 5y10mo. Un mes o un año no tiene una longitud fija, así que estas operaciones mueven fechas según el calendario ($date + 1mo conserva el día del mes cuando puede) y se rechazan donde se necesita una longitud fija, como en wait(1mo) o 1mo.hours.
El editor completa los campos y métodos de cada tipo y muestra lo que hacen. Para cambiar el formato de un valor, como leer texto JSON o escribir filas como CSV, usa ->convert(): consulta Conversión entre formatos.
Fechas
Los datos de calendario de una fecha son campos: .year, .month, .day, .weekday, .quarter, .day_of_year, .week (el número de semana ISO) y .days_in_month. .is_past, .is_future, .is_today y .is_weekend la comparan con el momento actual, así que sirven para plantillas:
<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) y ->end_of(unit) dan el primer y el último instante del day, week, month, quarter o year en que cae una fecha, que es lo que necesita un informe de «los pedidos de este mes». Una semana empieza el primer día de la configuración regional (lunes en en-GB, domingo en en-US), o el que indique 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-16La aritmética de calendario cuenta unidades completas. $date + 1y6mo mueve una fecha por años y meses, y también ->add(), que acepta cualquier combinación de years:, months:, weeks: y days: (->subtract() la mueve hacia atrás). Un mes conserva el día del mes cuando puede, así que el 31 de enero más un mes es el último día de febrero. Para horas y minutos, suma o resta una duración:
<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:30Una fecha solo se mueve con una duración. $date + 1 es un error, porque un número simple son segundos en todos los demás casos, y también lo es sumar un booleano, una lista u otra fecha. Escribe la unidad ($date + 3d). El único caso en que un número representa una fecha es una marca de tiempo Unix, los segundos desde 1970, que ->to_date() lee y ->timestamp() devuelve:
<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() // 1795996800Restar una fecha de otra da el tiempo exacto entre ellas como duración. ->since(other, in: unit) cuenta días, semanas, meses o años completos, como lo hace un cumpleaños. ->is_same(other, unit) pregunta si dos fechas comparten un día (por defecto), una semana, un mes, un trimestre o un año:
<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) // trueNow viene del reloj del equipo, así que en las pruebas @with_clock(date, fn) lo fija para @now(), @today(), los campos anteriores y @format_relative().
Trabajar con texto
El texto tiene funciones auxiliares para las tareas que se repiten: cambiar la capitalización de un nombre, cortar por un separador, limpiar espacios y firmar una carga útil.
<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() y ->after() cortan en el primer separador, o en el último con last, y devuelven el texto completo cuando el separador no aparece. ->wrap(width: 60) parte el texto entre palabras para que quepa en un ancho, como @terminal_width(). ->is_numeric() es verdadero para textos como '42' o '-3.5'.
->contains(), ->starts_with(), ->ends_with(), ->index_of() (la última coincidencia con last) y ->replace() distinguen mayúsculas y minúsculas exactamente. Pasa ignore_case para que coincidan mayúsculas y minúsculas por igual:
<let name="query" value="'TEA'" />
<echo value="'Green tea'->contains($query, ignore_case)" /> <!-- true -->$query = 'TEA'
echo 'Green tea'->contains($query, ignore_case) // truePara comprobar un webhook, calcula la firma con ->hmac(key) (SHA-256 por defecto, o sha1 o sha512) y compárala con @secure_equals(), que tarda lo mismo sin importar cuánto coincidan las dos:
<let name="body" value="'{"id": 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() y ->sha512() devuelven hashes en hexadecimal. @escape_regex(text) escapa lo que escribió un usuario para que un patrón construido a partir de ello coincida solo con ese texto.
Listas y mapas
Las listas se comparan como conjuntos con ->difference(other), ->intersect(other) y ->union(other). Cada una mantiene el orden de la primera lista, devuelve cada elemento una sola vez y compara los elementos con ==, o con lo que devuelva by: para cada uno:
<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) cuenta los elementos de cada clave, ->take_while(fn) y ->skip_while(fn) se detienen en el primer elemento que falla, ->window(size, step?) devuelve secuencias solapadas, y ->replace_at(index, item) devuelve una copia con un elemento cambiado:
<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']Más y menos comunes: common
->common(count?, least, by?) cuenta cuántas veces aparece cada elemento y devuelve los elementos en ese orden, cada uno una vez. Sin least primero aparecen los más comunes; con least aparecen primero los más raros. count conserva solo esa cantidad desde el principio, y sin él obtienes todos los elementos distintos. Los elementos que aparecen el mismo número de veces mantienen el orden en que aparecen por primera vez en la lista, y cada elemento se devuelve tal cual, así que los números siguen siendo 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 mostby: decide qué cuenta como el mismo elemento. Aquí 'Tea' y 'tea' se cuentan juntos porque ambos se pasan a 'tea', y se devuelve el que apareció primero:
<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, twicePara multiplicar entre sí los tres números más comunes, tómalos con ->common(3) y multiplícalos 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 756Los mapas tienen las mismas funciones de callback que las listas, recibiendo primero el valor y luego la clave: ->filter(), ->reject(), ->any(), ->all(), ->find() (que devuelve { key, value }), ->reduce(), ->sort(by:) y ->map(). ->map_keys(fn) renombra cada clave, recibiendo primero la clave y luego el 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' }Convertir entre formatos: convert
Los datos cambian de formato constantemente: una API responde en JSON, un archivo de configuración es YAML, una hoja de cálculo se guarda como CSV. Todo valor tiene un único método para ello, ->convert(), y se lee como una frase: convierte desde este formato, a aquel.
from: lee texto escrito en un formato y te devuelve los valores que contiene. to: escribe un valor en un formato. Usa ambos para convertir directamente un formato en otro.
| Formato | from: lo lee |
to: lo escribe |
|---|---|---|
json |
mapas, listas, textos, números | texto json |
yaml |
mapas, listas, textos, números | texto yaml |
csv |
una lista de filas | texto csv |
markdown, latex |
un documento | con KScript.Document |
html |
desde Markdown con KScript.Markdown, desde documentos con KScript.Document |
Leer texto: from
from: acepta texto, un bloque de texto como un bloque ```yaml o ```csv, un valor json o csv, o una respuesta HTTP (su cuerpo):
<let name="order" value="'{"fruit": "apple", "count": 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 mapCSV tiene por defecto una línea de encabezado, que nombra las claves de cada fila. Escribe not header cuando cada línea sea un dato, y cada fila será entonces una lista de sus celdas:
<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 tooComprobarlo contra un tipo: as
as: comprueba lo leído contra un tipo y lo convierte en registros, de modo que un campo que falta o es incorrecto es un error en la línea que lo lee, y no una sorpresa más adelante. Una lista de registros se escribe como lo haría una declaración, 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 3Escribir un formato: to
to: escribe cualquier valor: mapas y listas como JSON o YAML, y una lista de filas como CSV. indented reparte el JSON en varias líneas, y headers: elige y ordena las columnas 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 forAmbos a la vez
Usa from: y to: juntos para cambiar un formato por otro sin manipular los valores intermedios:
<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 jsonAtajos: from y to
Cuando solo lees o solo escribes, ->from(type: json) y ->to(type: csv) dicen lo mismo con menos palabras. Aceptan las mismas opciones que ->convert():
<let name="order" value="'{"fruit": "apple"}'->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() es la única forma de cambiar un formato, así que las formas antiguas de un método por formato (->json(), ->yaml(), ->csv(), ->markdown(), ->to_json(), ->to_yaml(), ->to_csv(), y los ->html(), ->latex() y ->markdown() de un documento) son errores que muestran el ->convert() que debes escribir, con una corrección en el editor.
Leer texto estructurado
Los datos suelen llegar como texto: un registro por línea, grupos de líneas separados por una línea en blanco, o un dibujo hecho con caracteres. Estos métodos convierten ese texto en listas con las que puedes trabajar.
Líneas y bloques
->lines() devuelve un texto por línea. ->blocks() divide el texto en los renglones en blanco, de modo que cada bloque es un grupo de líneas. Un salto de línea simple se mantiene dentro de un bloque; solo una línea vacía inicia uno nuevo:
<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() en lugar de una función es una forma abreviada de fn(block) => $block->lines(): el método se llama sobre cada elemento, igual que .name lee el campo de cada elemento. Funciona en cualquier lugar donde vaya una función, como ->filter(.is_empty()) o ->sort(by: .age).
Dividir una lista: split
Cuando ya tienes una lista, ->split(separator) la corta en listas allí donde aparece el elemento separador, y descarta el separador. Indica un valor para buscar con ==, o una comprobación que sea verdadera para el 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() sobre un texto corta el texto; ->split() sobre una lista corta la lista.
Números en un texto: numbers
->numbers() devuelve todos los números escritos en el texto, en orden, así que no necesitas un patrón para ello. Un signo menos cuenta como signo cuando va justo delante de un número y no hay nada pegado a su izquierda, como en x=-3; entre dos números, como en 1-3, es un guion, así que obtienes 1 y 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]Dibujos con caracteres: grid
->grid() convierte líneas de caracteres en filas de caracteres individuales, de modo que $grid[row][column] es un carácter. La fila 0 es la línea superior y la columna 0 el primer carácter:
<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 characterRecorrer filas y columnas: cells
->cells() lee una cuadrícula como leerías una tabla. Por sí solo, o con rows, devuelve cada fila; con columns devuelve cada columna, de arriba abajo. Así es como recorres una cuadrícula en cualquiera de las dos direcciones:
<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 rowsrow: elige una fila y column: una columna, contando desde 0, y -1 es la última. Indica ambas para obtener la única celda donde se cruzan:
<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 characterLas líneas pueden tener longitudes distintas, como en un mapa irregular. Entonces una columna omite las filas demasiado cortas para llegar a ella, así que no se inventa nada para rellenar el hueco:
<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 con cualquier lista de listas, no solo con una cuadrícula: [[1, 2], [3, 4]]->cells(columns) es [[1, 3], [2, 4]], que convierte filas en columnas.
Encontrar cosas en una cuadrícula: positions_of
->positions_of(item) devuelve cada lugar donde aparece un elemento en una cuadrícula, como puntos con un .row y una .column, fila por fila y de izquierda a derecha. Si se le da una función, devuelve los lugares donde la función es verdadera para la celda:
<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 .Los puntos funcionan bien con ->combinations(2), que devuelve cada par una sola vez con el punto anterior primero. Una función con dos parámetros recibe los dos puntos del par uno a uno. Esto cuenta los cuadrados cuyas cuatro esquinas son todas árboles, aunque haya otros árboles entre las esquinas:
<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 themEncontrar formas: shapes
->shapes() encuentra formas en un texto, una lista, una cuadrícula o una lista 3D: cuadrados, rectángulos, líneas y círculos integrados, y máscaras, que son formas que tú dibujas. El texto se lee como lo lee ->grid(), una fila por línea y una celda por carácter, así que no hace falta llamar antes a ->grid(). Las celdas de una cuadrícula pueden contener cualquier cosa, así que para las formas integradas of: indica qué celdas forman la figura: un valor como '#', o una expresión regular como /[#@]/. Cada coincidencia se devuelve una vez, como { kind, points }, y cada punto es una celda { row, column, value }. Puede haber otras celdas entre los puntos de una 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 themSin rotated, las formas están rectas: los cuadrados y rectángulos tienen los lados horizontales y verticales, y las líneas van a lo ancho o hacia abajo. Con rotated, pueden estar inclinadas, así que un cuadrado puede ser un rombo y una línea puede ir en 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 cornerIndica varias formas para encontrarlas todas. Una coincidencia se devuelve una sola vez aunque encaje en más de una forma: un cuadrado también es un rectángulo, así que se devuelve como cuadrado, y .kind indica cuál es:
<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 tooUna línea necesita size:, cuántos puntos tiene. Un círculo necesita radius:, y distance: indica lo lejos que se considera: straight (en línea recta, el valor por defecto), steps (solo horizontal y vertical, lo que dibuja un rombo) o moves (las diagonales cuentan como uno, lo que dibuja un anillo cuadrado):
<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() también funciona con una lista de puntos, como la que devuelve ->positions_of() o las filas leídas de un csv. En ese caso cada punto cuenta, así que no hay of:: $trees->shapes(square, rotated).
Formas propias: 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 un bloque sólido de # de 2 por 2, dibújalo y pasa la máscara a ->shapes() por su nombre:
<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 1symbols 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 middlesymbols se justifica cuando las celdas no son caracteres sueltos. Una fila de asientos es una lista de palabras, y una lista de valores es una sola fila, así que la disposición necesita una letra para cada palabra:
<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() acepta una máscara o una lista de ellas, y rotated convierte cada una en todas las orientaciones que permita la entrada: de atrás hacia delante en una fila, a un cuarto, a media vuelta y a tres cuartos en una cuadrícula, y las 24 orientaciones en 3D. Las coincidencias de varias máscaras se devuelven juntas, cada una identificada por su .kind, y las máscaras y las formas integradas pueden buscarse en una sola llamada:
<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 matchLos símbolos de una máscara pueden cambiarse donde se usa, como cualquier campo: Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) es la misma V de cualquier cosa salvo ..
Una línea en blanco en la disposición empieza la capa siguiente, primero la capa superior, igual que una línea en blanco en el texto en el que busca la máscara. Todas las capas tienen el mismo número de filas, y cada punto de una coincidencia en 3D también tiene un layer. Una lista 3D ($cube[layer][row][column]) se lee de la misma 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 belowUna máscara con menos capas o filas que la entrada se desliza por toda ella: una máscara de una sola línea se prueba en cada fila de una cuadrícula, y una máscara plana en cada capa de un texto 3D o de una lista 3D. Una máscara con más es un error que lo indica, por ejemplo "Step tiene 2 capas, y esto es una cuadrícula."
Mask es un tipo que puedes escribir para un parámetro o un campo. Acepta cualquier tipo que extienda Mask, ya sea el tipo en sí (Block) o uno derivado de él (Block(symbols: ...)), y Mask[] acepta una lista de ellos:
<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 countA 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.
Trabajar con secuencias
Multiplicar: product
->product(fn?) multiplica los elementos, como ->sum() los suma. Dada una función, multiplica lo que la función devuelve para cada elemento. Los números enteros se mantienen exactos sea cual sea su tamaño:
<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() // 508298490Totales acumulados: scan
->scan(fn(total, item), initial?) funciona como ->reduce(), pero conserva cada total parcial, así que se ve cómo se construye el resultado. Sin initial, el primer elemento es el primer 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 itCada selección: combinations
->combinations(size) da todas las formas de elegir size elementos de la lista cuando el orden de los elementos elegidos no importa. Cada selección mantiene los elementos en el orden de la lista, y ningún elemento se elige dos veces en la misma selección.
Elegir 2 de ['tea', 'milk', 'juice'] funciona así: empieza con tea y combínalo con cada elemento que viene después (milk, y luego juice); después empieza con milk y combínalo con cada elemento que viene después (juice). juice no tiene nada después, así que no hay nada más. ['milk', 'tea'] nunca aparece, porque es la misma selección 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']]Un uso habitual es comprobar todos los pares, por ejemplo para encontrar los dos precios que suman un 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 isUna función con un parámetro por cada elemento elegido recibe los elementos uno a uno, así que puedes nombrarlos en lugar de leer $two[0] y $two[1]. Esto funciona para cualquier tamaño: selecciones de 3 llenan fn(first, second, third). Una función con un solo parámetro sigue recibiendo la selección completa:
<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 listComo los elementos elegidos llenan los parámetros, una función así no recibe también el índice: con pares, fn(first, second) son los dos elementos del par.
Todos los órdenes: permutaciones
->permutations(size?) da todos los órdenes posibles, donde el orden sí importa, así que ['tea', 'milk'] y ['milk', 'tea'] aparecen ambos. Sin size cada orden usa todos los elementos:
<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 secondLas combinaciones y las permutaciones crecen muy rápido (10 elementos tienen 3.628.800 órdenes), así que a partir de un millón de listas se detienen con un error de Limit en lugar de quedarse sin memoria.
Dar la vuelta: rotate
->rotate(by) mueve cada elemento by posiciones hacia el principio, y los que caen por delante pasan al final. Un by negativo gira en sentido contrario:
<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 frontAñadir métodos a un tipo: extend
extend añade tus propios métodos a un tipo, incorporado o propio. Dentro, cada fn es un método, y $this es el valor sobre el que se llama:
<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 método no puede tomar el nombre de uno que el tipo ya tenga, así que una errata o un choque nunca cambia lo que hace un método incorporado. Para reemplazar uno a propósito, escribe 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')
}En XML, extend es <extend type="date"> que contiene elementos <fn>, y override fn es <fn override="true">.
Dónde se aplican las extensiones. Los bloques extend de un archivo se aplican en ese archivo y en todos los archivos que lo importen. En un proyecto (una carpeta con kscript.json), todos los archivos de la carpeta extensions/ se aplican a todos los scripts, pruebas y páginas del proyecto, sin necesidad de importarlos. Sepáralos como quieras, por ejemplo un archivo por tipo:
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 como punto de partida. Para guardarlos en otro lugar, indica carpetas o globs en kscript.json, lo que sustituye a la carpeta por defecto: "extensions": ["extensions", "shared/**/*.kscript"]. Que dos archivos de extensión añadan el mismo método al mismo tipo es un error que indica ambos. El extend propio de un script (o de una importación) tiene prioridad sobre el del proyecto.
El editor completa y comprueba los métodos de extensión solo donde se aplican: en un archivo que no los declara, no los importa y (a través del proyecto) no obtiene ->api_date() en las fechas. @today()->api_date() sigue siendo un método desconocido. Al pasar el cursor se muestra la documentación del método /// y el archivo que lo añade, y ir a la definición abre ese archivo.