KScript ドキュメント
JA

言語

英語から自動翻訳されています。原文は英語です。

言語

値とメソッド

値は文字列、数値、真偽値、リスト、マップ、日付、関数、null、そして値パッケージが追加するもの(ファイル、HTTPレスポンス)です。すべての値はメソッドを持ち、->で呼び出して連結できます:

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

pluck(key)を使うと、各項目から順にフィールドを読み取れます。pluckにキーのリストを渡すと、項目ごとに新しいマップを1つずつ作ります。キーは修飾なしの名前、引用符付きの文字列、または変数で指定できます。

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

マップに存在しないキーはnullになります。型付きレコードは通常どおりフィールドチェックを行います。入力リストが空なら[]になり、pluck([])は入力項目ごとに空のマップを1つずつ返します。同じキーが繰り返されても、要求された順序で1回だけ現れます。

リストに対するcontains(value)、index_of(value)、remove(value)、count_of(value)は==で比較します。例えば[1, '1']->count_of(1)は2になります。unique()は厳密な等価(===)を使うので、[1, '1']->unique()は両方の項目を残します。

is_empty()は、文字列では0文字、リストでは0個の項目、マップでは0個のキーを意味します。空白だけの入力も受け付けるために$text->is_empty()を使っていた場合は、その動作を維持するために$text->is_blank()を使ってください。

テキスト ->is_empty() ->is_blank()
'' true true
' ' false true
'hello' false false

数値は常に指数表記ではなく普通の桁で書かれます: echo 10 ** 20は100000000000000000000と表示され、echo 0.1 ** 20は0.00000000000000000001と表示されます。整数はどんな大きさでも正確です: 123456789 * 987654321は121932631112635269、2 ** 100は1267650600228229401496703205376で、テキストやJSONから読み取った20桁のidもすべての桁を保持します。+、-、*、%、**、/(割り切れる場合)、->sum()、->product()、@gcd、@lcm、@factorialはすべて正確なままです。小数、@sqrtなどは通常の浮動小数点数で扱われます。小数は有効数字15桁で表示されるので、0.1 + 0.2は0.3と表示されます。整数は約30,000桁まで大きくなることができ、それを超えると制限エラーで停止します。

テキストでは、->count()と位置(->slice()、->index_of()、$text[0]内)は、ほとんどの文字を1か所として数え、絵文字のような文字は2か所として数えます。どのメソッドもそのような文字を途中で切ることはありません: ->chars()、->first()、->last()、->reverse()は読者が見るとおりの完全な文字単位で動作し、->slice()と->truncate()は、その中で切れてしまう位置を手前に移動させます。

値についての単純な事実はフィールドで、括弧を付けずにドットで読み取ります。マップのキーと同じ書き方です:

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

つまり$response.status、$file.size、$url.host、$e.statusはフィールドであり、引数を取るか処理を行うものはメソッドです: $response->convert(from: json)、$file->read_text()、$day->format('yyyy')。trueかfalseを返す名前はis_またはhas_で始まります: $response.is_ok、$ip.is_private、$list->is_empty()、$map->has(key)。

時間の長さは期間です。数値と単位を引用符なしで続けて書きます。例えば500ms、30s、10m、2h、1d、1wで、さらに組み合わせることもできます(1h30m)。時間の長さを取るものはすべて期間を取ります: wait(500ms)、@api($url, options: { timeout: 30s })、$cache->set(key, value, ttl: 10m)。単なる数値は常に秒です。

年と月はyとmoです(mは分です): 1y、6mo、5y10mo。月や年は固定の長さを持たないので、これらはカレンダーに従って日付を動かします($date + 1moは可能な場合は日の番号を保ちます)。wait(1mo)や1mo.hoursのように固定の長さが必要な場所では拒否されます。

エディタは各型のフィールドとメソッドを補完し、その働きを表示します。値の形式を変えるには、例えばJSONテキストの読み取りや行のCSV書き出しなどには->convert()を使います。形式間の変換を参照してください。

日付

日付のカレンダー上の事実はフィールドです: .year、.month、.day、.weekday、.quarter、.day_of_year、.week(ISO週番号)、.days_in_month。.is_past、.is_future、.is_today、.is_weekendは日付を現在時刻と比較するので、テンプレートに向いています:

<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)と->end_of(unit)は、日付が属するday、week、month、quarter、またはyearの最初と最後の瞬間を返します。これは「今月の注文」のようなレポートに必要なものです。週はロケールの最初の曜日から始まります(en-GBでは月曜、en-USでは日曜)。または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

カレンダーの計算は単位の整数個を数えます。$date + 1y6moは年と月で日付を動かし、->add()も同様で、years:、months:、weeks:、days:の任意の組み合わせを取ります(->subtract()では後ろに動かします)。月は可能な場合は日の番号を保つので、1月31日に1か月足すと2月の最終日になります。時間や分については、期間を足すか引きます:

<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

日付は期間によってのみ動きます。$date + 1はエラーです。他の場所では単なる数値は秒を意味するからです。また、真偽値、リスト、別の日付を足すこともエラーです。単位を書いてください($date + 3d)。数値が日付を表す唯一の場所はUnixタイムスタンプ、つまり1970年からの秒数で、->to_date()はそれを読み取り、->timestamp()はそれを返します:

<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

ある日付から別の日付を引くと、その間の正確な時間が期間として得られます。->since(other, in: unit)は誕生日のように、日、週、月、年の整数個を数えます。->is_same(other, unit)は2つの日付が同じ日(既定)、週、月、四半期、年にあるかを問います:

<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はコンピュータの時計から得られるので、テストでは@with_clock(date, fn)が@now()、@today()、上記のフィールド、@format_relative()のために値を固定します。

テキストの扱い

テキストには、繰り返し出てくる作業のためのヘルパーがあります。名前の大文字・小文字の変換、区切り文字での分割、空白の整理、ペイロードの署名などです。

<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()と->after()は最初の区切り文字で切り、lastを付けると最後の区切り文字で切ります。区切り文字がない場合はテキスト全体を返します。->wrap(width: 60)は、@terminal_width()のような幅に収まるように単語の間で改行します。->is_numeric()は'42'や'-3.5'のようなテキストに対して真になります。

->contains()、->starts_with()、->ends_with()、->index_of()(最後の一致はlast)と->replace()は大文字と小文字を正確に区別して一致させます。大文字と小文字を区別せずに一致させるにはignore_caseを渡してください:

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

Webhookの署名を確認するには、->hmac(key)で署名を計算し(デフォルトはSHA-256です。sha1またはsha512も使用できます)、その結果を@secure_equals()と比較します。この比較は、一致する部分の長さに関係なく、常に同じ時間がかかります。

<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()、->sha512()は、ハッシュを16進数で返します。@escape_regex(text)は、ユーザーが入力した文字列をエスケープするので、そこから作ったパターンはその文字列だけに一致します。

リストとマップ

リストは->difference(other)、->intersect(other)、->union(other)によって集合として比較されます。それぞれ最初のリストの順序を保ち、各項目を一度だけ返し、==で項目を照合するか、各項目についてby:が返す値で照合します:

<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)は各キーの項目数を数え、->take_while(fn)と->skip_while(fn)は最初に失敗した項目で停止し、->window(size, step?)は重なり合う連続部分を返し、->replace_at(index, item)は一つの項目を変更した複製を返します:

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

最も多い、最も少ない: common

->common(count?, least, by?)は各項目の出現回数を数え、その順に項目を一度ずつ返します。leastを指定しなければ最も多いものが先頭に来ます。leastを指定すると最も少ないものが先頭に来ます。countは先頭から指定した数だけ残し、指定しなければ異なるすべての項目を返します。出現回数が同じ項目は、リスト内で最初に現れた順序を保ちます。各項目はそのままの形で返るので、数値は数値のままです:

<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:は、何を同じ項目とみなすかを決めます。ここでは'Tea'と'tea'はどちらも'tea'に小文字化されるため、一緒に数えられ、先に現れた方が返されます:

<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

上位3つの数値を掛け合わせるには、->common(3)で取り出し、->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

マップにもリストと同じコールバックがあり、値、次にキーの順に渡されます。->filter()、->reject()、->any()、->all()、->find()(これは{ key, value }を返します)、->reduce()、->sort(by:)、->map()です。->map_keys(fn)は各キーの名前を変更するもので、キー、次に値を受け取ります:

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

形式間の変換: convert

データは形式間で絶えず移動します。APIはJSONで応答し、設定ファイルはYAML、スプレッドシートはCSVで保存されます。すべての値はこれらのために一つのメソッド->convert()を持ち、それは文のように読めます。この形式から、あの形式へ変換する、という意味です。

from:は、ある形式で書かれたテキストを読み取り、その中の値を返します。to:は、値をある形式で書き出します。両方を渡すと、ある形式を直接別の形式に変換できます。

形式 from:が読み取る to:が書き出す
json マップ、リスト、テキスト、数値 jsonテキスト
yaml マップ、リスト、テキスト、数値 yamlテキスト
csv 行のリスト csvテキスト
markdown, latex ドキュメント KScript.Documentを使用
html KScript.Markdownを使ったMarkdownから、KScript.Documentを使ったドキュメントから

テキストの読み取り: from

from:は、テキスト、```yamlや```csvのようなテキストブロック、jsonやcsvの値、またはHTTPレスポンス(その本文)を受け取ります:

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

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

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

CSVはデフォルトでヘッダー行があり、各行のキーを名前付けします。すべての行がデータである場合はnot headerを書きます。すると各行はセルのリストになります:

<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

型に照らして確認する: as

as:は、読み取った内容を型に照らして確認し、レコードに変換します。そのため、欠けているフィールドや誤った型のフィールドは、後で予期せぬ事態を起こすのではなく、それを読み取った行でエラーになります。レコードのリストは、宣言が書かれるのと同じように、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

形式への書き出し: to

to:は任意の値を書き出します。マップとリストはJSONまたはYAMLとして、行のリストはCSVとして書き出されます。indentedはJSONを複数行に分割し、headers:は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

両方を一度に

from:とto:を一緒に指定すると、その間の値を扱わずに一つの形式を別の形式へ変換できます:

<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

短縮形: from と to

読み取るだけ、または書き出すだけの場合は、->from(type: json)と->to(type: csv)で同じことを少ない言葉で表せます。これらは->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()が形式を変換する唯一の方法なので、形式ごとに一つずつあった古い書き方(->json()、->yaml()、->csv()、->markdown()、->to_json()、->to_yaml()、->to_csv()、およびドキュメントの->html()、->latex()、->markdown())はエラーになります。エラーには、代わりに書くべき->convert()が示され、エディターで修正できます。

構造化されたテキストの読み取り

データは多くの場合テキストとして届きます。1行に1レコード、空行で区切られた行のグループ、または文字で描かれた図などです。これらのメソッドは、そのテキストを扱えるリストに変換します。

行とブロック

->lines()は、行ごとに一つのテキストを返します。->blocks()は、代わりに空行でテキストを分割するので、各ブロックは行のグループになります。単一の改行はブロック内に残り、空行だけが新しいブロックを始めます:

<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()と書くのはfn(block) => $block->lines()の短縮形です。各項目に対してメソッドが呼ばれ、.nameが各項目のフィールドを読むのと同じです。->filter(.is_empty())や->sort(by: .age)など、関数を置けるところならどこでも使えます。

リストの分割: split

すでにリストがある場合、->split(separator)は区切り項目が現れるところでリストを切り分け、区切り項目は取り除きます。==で照合する値を指定するか、区切り項目に対して真となる判定を渡してください:

<let name="lines" value="['tea', 'milk', '', 'juice']" />

<echo value="$lines->split('')" /> <!-- [['tea', 'milk'], ['juice']] because '' is the separator -->
<echo value="$lines->split(.is_empty())" /> <!-- [['tea', 'milk'], ['juice']] because the check is true for '' -->
<echo value="[5, 0, 7, 8, 0]->split(0)" /> <!-- [[5], [7, 8], []] because 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()はテキストを切り、リストに対する->split()はリストを切ります。

テキスト中の数値: numbers

->numbers()は、テキスト中に書かれたすべての数値を順番に返すので、そのためのパターンを書く必要はありません。マイナス記号は、x=-3のように左側に何も連続していない数値の直前にある場合は符号として扱われます。1-3のように二つの数値の間にあるときはダッシュとなり、結果は1と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]

文字で描かれた図: grid

->grid()は、文字の行を一文字ずつの行に変換するので、$grid[row][column]は一文字です。0行目が一番上の行、0列目が最初の文字です:

<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

行と列を順にたどる: cells

->cells()は、表を読むように格子を読みます。単独で使うかrowsと使うと、すべての行を返します。columnsを使うと、すべての列を上から下へ返します。これが、格子をどちらの方向にもループする方法です:

<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:は一つの行を、column:は一つの列を選びます。どちらも0から数えられ、-1は最後の要素です。両方を指定すると、その二つが交わる一つのセルを取得できます:

<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

ぎざぎざのあるマップのように、行の長さが異なる場合があります。その場合、列はそこに届かない短い行をスキップするので、隙間を埋めるために何かが作られることはありません:

<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()は、格子だけでなく任意のリストのリストに対して動作します。[[1, 2], [3, 4]]->cells(columns)は[[1, 3], [2, 4]]と同じで、行を列に変換します。

格子内で探す: positions_of

->positions_of(item)は、格子内で項目が現れるすべての位置を、.rowと.columnを持つ点として、行ごと左から右の順で返します。関数を渡すと、セルについてその関数が真となる位置を返します:

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

点は、各組を一度だけ先に現れた点を先頭にして返す->combinations(2)と相性が良いです。二つの引数を取る関数には、その組の二つの点が一つずつ渡されます。以下は、四隅がすべて木である正方形を、その間に他の木があっても数える例です:

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

<let name="trees" value="$field->grid()->positions_of('#')" />
<echo value="$trees->combinations(2)->count_of(fn(left, right) {
    // only two trees on the same row can be a square's top corners
if $left.row != $right.row {
  return false
}
// the gap between them is the square's width, so the bottom corners sit that many rows down
    $size = $right.column - $left.column
    return $trees->contains({ row: $left.row + $size, column: $left.column })
      and $trees->contains({ row: $left.row + $size, column: $right.column })
  })" />
<!-- 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them -->
$field = ```text
#.##.
.....
.#...
##.##
```

$trees = $field->grid()->positions_of('#')
echo $trees->combinations(2)->count_of(fn(left, right) {
  // only two trees on the same row can be a square's top corners
  if $left.row != $right.row {
    return false
  }
  // the gap between them is the square's width, so the bottom corners sit that many rows down
  $size = $right.column - $left.column
  return $trees->contains({ row: $left.row + $size, column: $left.column })
    and $trees->contains({ row: $left.row + $size, column: $right.column })
})
// 1 because only the trees at columns 0 and 3 of row 0 have trees 3 rows below both of them

図形の検出: shapes

->shapes() は、テキスト、リスト、グリッド、3Dリストの中から図形を見つけます。組み込みの正方形、長方形、直線、円、そして描いて作るマスクです。テキストは ->grid() と同じように読まれ、1行が1つの行、1文字が1つのセルとして扱われるため、事前に ->grid() を呼ぶ必要はありません。グリッドのセルには任意の値を入れられます。組み込みの図形の場合、of: でどのセルが図形を構成するかを指定します。値(例: '#')でも、正規表現(例: /[#@]/)でも指定できます。一致したものはそれぞれ { kind, points } として一度だけ返され、各点はセル { row, column, value } です。図形の点の間には、他のセルがあってもかまいません:

<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

rotated を指定しない場合、図形は水平・垂直に配置されます。正方形と長方形の辺は水平・垂直で、直線は横または縦に伸びます。rotated を指定すると、図形は傾くことができ、正方形がひし形になったり、直線が斜めになったりします:

<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

複数の図形名を指定すると、それらすべてを見つけます。一つの一致が複数の図形に当てはまる場合でも、一度だけ返されます。たとえば正方形は長方形でもあるため、正方形として返されます。どの図形かは .kind で確認できます:

<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

直線には size:(点の数)が必要です。円には radius: が必要で、distance: で距離の測り方を指定します。straight(直線距離、デフォルト)、steps(縦横のみ。ひし形になります)、moves(斜めも1として数える。正方形の輪になります)のいずれかです:

<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() は、->positions_of() が返す点や、CSVから読み込んだ行などの点のリストにも使えます。その場合はすべての点が対象となるため of: は不要です: $trees->shapes(square, rotated)。

独自の図形: マスク

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.

# の2x2の塊を見つけるには、それを描いてマスクを作り、名前を使って ->shapes() に渡します:

<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 は、セルが1文字でない場合に役立ちます。座席の並びは単語のリストで、値のリストは1行なので、各単語に文字を割り当てる必要があります:

<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() は1つのマスクまたはそのリストを受け取り、rotated は各マスクを入力が許すすべての向きに変換します。行は前後逆、グリッドでは4分の1、2分の1、4分の3回転、3Dでは24通りのすべての向きです。複数のマスクの一致は、それぞれの .kind で名前付けされ、まとめて返されます。マスクと組み込みの図形は、1回の呼び出しで一緒に検索できます:

<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

マスクのシンボルは、任意のフィールドと同様に使用箇所で変更できます。Fork(symbols: { t: fn(cell) => $cell != '.', '~': any }) は、. を除くどの値でもVとして扱います。

レイアウトの空行は、マスクが検索するテキストの空行と同じように、次のレイヤーの始まりを示します。上のレイヤーが先頭です。すべてのレイヤーの行数は同じである必要があり、3Dの一致の各点にも layer があります。3Dリスト($cube[layer][row][column])も同じように読まれます:

<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

レイヤーや行数が入力より少ないマスクは、入力全体をスライドします。1行のマスクはグリッドの各行で試され、平面のマスクは3Dテキストや3Dリストの各レイヤーで試されます。入力より多いマスクはエラーになり、"Step has 2 layers, and this is one grid." のように理由が示されます。

Mask は、パラメータやフィールドに指定できる型です。Mask を拡張する任意の型を受け取ります。型そのもの(Block)でも、そこから作られた型(Block(symbols: ...))でもよく、Mask[] はそれらのリストを受け取ります:

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

数列を扱う

掛け算: product

->product(fn?) は、->sum() が足し算をするように、項目を掛け合わせます。関数を与えると、各項目に対する関数の結果を掛け合わせます。整数はどれだけ大きくても正確に保たれます:

<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

途中の合計: scan

->scan(fn(total, item), initial?) は ->reduce() と似ていますが、途中のすべての合計を保持するため、結果がどのように積み上がっていくかが分かります。initial を指定しない場合は、最初の項目が最初の合計になります:

<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

すべての組み合わせ: combinations

->combinations(size) は、要素の順序が問われない場合に、リストから size 個の要素を選ぶすべての組み合わせを返します。各組み合わせは、要素をリストの順序のまま保持し、同じ組み合わせ内で同じ要素を二度選ぶことはありません。

['tea', 'milk', 'juice'] から 2 個を選ぶ場合は次のように動作します。まず tea から始めて、その後ろの各要素(milk、次に juice)と組にします。次に milk から始めて、その後ろの各要素(juice)と組にします。juice の後ろには要素がないため、これ以上はありません。['milk', 'tea'] は ['tea', 'milk'] と同じ組み合わせになるため、現れません:

<let name="drinks" value="['tea', 'milk', 'juice']" />

<echo value="$drinks->combinations(2)" />
<!-- [['tea', 'milk'], ['tea', 'juice'], ['milk', 'juice']] because 3 drinks give 3 ways to pick 2 -->

<echo value="$drinks->combinations(3)" />
<!-- [['tea', 'milk', 'juice']] because there is only one way to pick all 3 -->

<echo value="$drinks->combinations(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']]

よくある用途は、すべての組を調べることです。たとえば、合計金額になる 2 つの価格を見つける場合などです:

<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

選ばれた要素の数だけパラメーターを持つ関数は、要素を一つずつ受け取るため、$two[0] と $two[1] を読む代わりに名前を付けて使えます。これはどのサイズにも使えます。3 個の組み合わせなら fn(first, second, third) を埋めます。パラメーターが 1 つの関数は、組み合わせ全体を受け取ります:

<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

選ばれた要素がパラメーターを埋めるため、このような関数はインデックスを同時には受け取りません。組が 2 個の場合、fn(first, second) はその組の 2 つの要素です。

すべての順序: 順列

->permutations(size?) は、順序が重要な場合のすべての並び順を返すため、['tea', 'milk'] と ['milk', 'tea'] の両方が含まれます。size がない場合、各並び順はすべての要素を使います:

<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

組み合わせと順列は急速に増えます(10 要素には 3,628,800 通りの並び順があります)。そのため、100 万件を超えるリストでは、メモリ不足になる代わりに Limit エラーで停止します。

向きを変える: rotate

->rotate(by) は、すべての要素を先頭方向へ by 個ずつずらし、先頭から押し出された要素は末尾に回します。負の by は逆方向に回します:

<let name="week" value="['mon', 'tue', 'wed', 'thu']" />
<echo value="$week->rotate(1)" /> <!-- ['tue', 'wed', 'thu', 'mon'] because mon moves from the front to the end -->
<echo value="$week->rotate(-1)" /> <!-- ['thu', 'mon', 'tue', 'wed'] because thu moves from the end to the front -->
$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

型へのメソッドの追加: extend

extend は、組み込み型または独自の型に独自のメソッドを追加します。ブロック内の各 fn はメソッドであり、$this は呼び出された対象の値です:

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

メソッドは、その型に既にある名前を付けることはできません。そのため、綴り誤りや名前の衝突によって組み込みメソッドの動作が変わることはありません。意図的に置き換えるには 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')
}

XML では、extend は <fn> 要素を含む <extend type="date"> であり、override fn は <fn override="true"> です。

拡張が適用される場所。 ファイル内の extend ブロックは、そのファイル内と、それをインポートするすべてのファイルに適用されます。プロジェクト(kscript.json を含むフォルダー)では、extensions/ フォルダー内のすべてのファイルが、インポートなしでプロジェクト内のすべてのスクリプト、テスト、ページに適用されます。たとえば型ごとに 1 ファイルなど、好きなように分割できます:

テキスト
extensions/
  date.kscript        extend date { … }
  list.kscript        extend list { … }
  text/
    slug.kscript      extend string { … }

kscript make extension date --methods api_date,is_payday は、開始点として extensions/date.kscript を書き込みます。別の場所に保存するには、既定のフォルダーを置き換える形で kscript.json にフォルダーまたはグロブを列挙します: "extensions": ["extensions", "shared/**/*.kscript"]。同じ型に同じメソッドを追加する 2 つの拡張ファイルはエラーになり、両方のファイル名が示されます。スクリプト自身の extend(またはインポートされたもの)は、プロジェクトのものより優先されます。

エディタは拡張メソッドを、それが有効な場所でのみ補完・チェックします。日付に対して->api_date()を宣言、インポート、またはプロジェクト経由で取得していないファイルでは、@today()->api_date()は依然として不明なメソッドです。ホバーするとメソッドの///ドキュメントと、そのメソッドを追加しているファイルが表示され、定義へ移動するとそのファイルが開きます。

Edit this page on GitHub