KScript 文档
ZH

语言

值与方法

值包括字符串、数字、布尔值、列表、映射、日期、函数和 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 传入一个键的列表,即可为每一项生成一个新映射。键可以是裸名称、带引号的字符串或变量。

<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([]) 为每个输入项生成一个空映射。重复的键只出现一次,并按请求的顺序排列。

在列表上,contains(value)、index_of(value)、remove(value) 和 count_of(value) 使用 == 进行比较。例如,[1, '1']->count_of(1) 得到 2。unique() 使用严格相等(===),因此 [1, '1']->unique() 会保留两项。

is_empty() 在字符串上表示零个字符,在列表上表示零项,在映射上表示零个键。如果你曾用 $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 位,超出后会以 Limit 错误停止。

对于文本,->count() 以及位置(在 ->slice()、->index_of() 和 $text[0] 中)大多数字符计为一个位置,而表情符号等字符计为两个。没有任何方法会把这样的字符切开:->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')。返回真或假的名称以 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 日加一个月得到 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) 判断两个日期是否处于同一天(默认)、同一周、同一月、同一季度或同一年:

<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()返回十六进制哈希值。@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

要把出现次数最多的三个数字相乘,先用->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' }

集合

集合是一组各不重复的项目。添加已存在的项目不会有任何效果,而且无论集合多大,判断某项目是否在其中都很快。集合写作列表的形式,再用as set转换为集合;也可以把变量或字段声明为set:

<let name="line" value="'rr?gb?r'" />
<let name="colours" value="$line->chars() as set" /> <!-- ['r', '?', 'g', 'b'] because each character goes in once -->
<echo value="($colours - ['?'])->count()" /> <!-- 3 because r, g and b are left once ? is taken away -->
$line = 'rr?gb?r'
$colours = $line->chars() as set   // ['r', '?', 'g', 'b'] because each character goes in once
echo ($colours - ['?'])->count()   // 3 because r, g and b are left once ? is taken away

集合最适合用来记录已经见过的内容。$seen: set = []创建一个空集合,+=向其中添加项目,in检查某项目是否存在。随着集合增大,这两个操作仍然很快:

<let name="seen" type="set" value="[]" />
<for each="place" in="['home', 'shop', 'home', 'park']">
  <if $place in $seen>
    <echo>back at { $place }</echo> <!-- back at home, once, because home was seen before -->
  </if>
  <set name="seen" op="+=" value="$place" />
</for>
$seen: set = []
for place in ['home', 'shop', 'home', 'park'] {
  if $place in $seen {
    echo "back at { $place }"   // back at home, once, because home was seen before
  }
  $seen += $place
}

+合并两个集合,-移除项目,->intersect()保留两者共有的项目。右侧可以是普通列表。set(of: string)是某一类型的集合,每个项目在加入时都会被转换为该类型,与带类型的列表一样。$set as list会把项目以列表形式返回。所有集合方法及示例见集合。

<type name="Post">
  <field name="title" type="string" />
  <field name="tags" type="set(of: string)" default="[]" />
</type>

<let name="post" value="Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })" />
<echo value="$post.tags" /> <!-- ['news', 'tech'] because the second 'news' is already in the set -->
<echo value="$post.tags->overlaps(['tech'])" /> <!-- true -->
<echo value="$post.tags->is_subset(of: ['news', 'tech', 'sport'])" /> <!-- true because both tags are in the list -->
type Post {
  title: string
  tags: set(of: string) = []
}

$post = Post({ title: 'Hello', tags: ['news', 'tech', 'news'] })
echo $post.tags                         // ['news', 'tech'] because the second 'news' is already in the set
echo $post.tags->overlaps(['tech'])     // true
echo $post.tags->is_subset(of: ['news', 'tech', 'sport']) // true because both tags are in the list

在格式之间转换: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()写法,编辑器中还附有修复建议。

读取结构化文本

数据常常以文本形式到达:每行一条记录、以空行分隔的多组行,或用字符绘制的图形。这些方法可将文本转换为便于处理的列表。

行与块

->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() 可在文本、列表、网格或三维列表中查找形状:内置的正方形、长方形、直线和圆形,以及您自己绘制的遮罩(masks)。文本按 ->grid() 的读取方式处理,每行为一行、每个字符为一个单元格,因此无需先调用 ->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(对角线距离计为一步,绘制出正方形环):

<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)。

自定义形状:遮罩(masks)

遮罩是您自己绘制的形状。内置形状只知道各点的位置;遮罩则精确规定每个单元格必须包含什么内容,包括空白单元格。将其声明为 extends Mask 所对应的类型,并在 layout 中绘制:一个文本块,每个字符对应一个单元格,用以描绘形状(也可以使用正则表达式,用于描述沿行延伸任意长度的形状:正则表达式布局)。每个字符都匹配与其内容相同的单元格。所有行共有的缩进不属于图案的一部分,因此请将其与周围的代码一同缩进。

要查找由 # 组成的实心 2×2 方块,请先绘制它,然后通过名称将遮罩传递给 ->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 仅用于那些具有特殊含义的字符。它将一个字符映射为其所匹配的内容:值(t: 'taken')匹配包含该值的单元格,正则表达式(/[#@]/)匹配文本符合该表达式的单元格,fn(cell) 匹配使其返回 true 的单元格,same 匹配必须都包含同一个值的单元格(见下文),any 匹配不属于该形状的单元格。any 单元格可以包含任何内容,可以超出输入的边缘,并且不计入匹配结果的各点。要查找 3×3 正方形四角的四棵树,中间可以有任意内容:

<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 就体现出其价值。一排座位是一个单词列表,而一个值的列表是一行,因此布局需要为每个单词分配一个字母:

<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() 可接受一个遮罩或一个遮罩列表,rotated 会将每个遮罩在输入允许的所有方向上进行变换:沿行从后向前,在网格中旋转四分之一、二分之一和四分之三圈,在三维中则有全部 24 种旋转方式。多个遮罩的匹配结果会一并返回,并通过各自的 .kind 命名,并且可以在一次调用中同时查找遮罩和内置形状:

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

布局中的空行表示下一层的开始,自上而下依次排列,与遮罩所匹配的文本中空行的含义相同。每一层的行数必须相同,三维匹配结果中的每个点也都有一个 layer。三维列表($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

层数或行数少于输入的遮罩会在整个输入上滑动:单行遮罩会沿网格的每一行尝试匹配,而单层遮罩则会在三维文本或三维列表的每一层中尝试匹配。层数或行数多于输入的遮罩会报错,并给出提示,例如"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

相同的单元格:same

迄今为止的所有符号都是将单元格与某个固定内容进行比较。same 则是比较单元格之间的关系:凡是以该字符绘制的单元格,都必须包含同一个值(无论是什么值),并且两个不同的 same 字符必须包含不同的值。same(...) 用于限定该值的范围,可以是一个值、一个正则表达式或一个 fn(cell)。要查找一个正读反读都相同的单词,例如 oxxo:

<type name="Mirror" description="Two letters, then the same two backwards, like 'abba'." extends="Mask">
  <field name="layout" default="```text
      xyyx
      ```" />
  <field name="symbols" default="{ x: same(/[a-z]/), y: same(/[a-z]/) }" />
</type>

<echo value="'ioxxoj'->shapes(Mirror)->count()" /> <!-- 1 because only 'oxxo' reads the same letters out and back -->
<echo value="'ioxxoj'->shapes(Mirror)->first().points->map(.value)" /> <!-- ['o', 'x', 'x', 'o'] because x is o and y is x there -->
<echo value="'aaaa'->shapes(Mirror)->count()" /> <!-- 0 because x and y are different characters, so they hold different letters -->
/// Two letters, then the same two backwards, like 'abba'.
type Mirror extends Mask {
  layout: ```text
    xyyx
    ```
  symbols: { x: same(/[a-z]/), y: same(/[a-z]/) }
}

echo 'ioxxoj'->shapes(Mirror)->count()                       // 1 because only 'oxxo' reads the same letters out and back
echo 'ioxxoj'->shapes(Mirror)->first().points->map(.value)   // ['o', 'x', 'x', 'o'] because x is o and y is x there
echo 'aaaa'->shapes(Mirror)->count()                         // 0 because x and y are different characters, so they hold different letters

任意长度的形状:正则表达式布局

图案的大小是固定的。布局也可以改用正则表达式,它会沿每一行逐个读取单元格,并匹配所需数量的单元格。每个单元格按其文本读取,匹配必须从单元格之间的边界开始并在边界结束。正则表达式布局不支持 symbols:使用 (?<name>...) 为某一部分命名,每个点的 symbol 即为其所在部分的名称:

<type name="PartNumber" description="A part number: digits side by side, each one named a digit." extends="Mask">
  <field name="layout" default="/(?&lt;digit>\d)+/" />
</type>

<let name="schematic">```text
    467..114
    ...*....
    ..35.633
    ```</let>

<echo value="$schematic->shapes(PartNumber)->count()" /> <!-- 4 because 467, 114, 35 and 633 are each a run of digits -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.column)" /> <!-- [0, 1, 2] because 467 fills the first three columns of row 0 -->
<echo value="$schematic->shapes(PartNumber)->first().points->map(.symbol)" /> <!-- ['digit', 'digit', 'digit'] because each cell fell in the digit part -->
/// A part number: digits side by side, each one named a digit.
type PartNumber extends Mask {
  layout: /(?<digit>\d)+/
}

$schematic = ```text
467..114
...*....
..35.633
```

echo $schematic->shapes(PartNumber)->count()                         // 4 because 467, 114, 35 and 633 are each a run of digits
echo $schematic->shapes(PartNumber)->first().points->map(.column)    // [0, 1, 2] because 467 fills the first three columns of row 0
echo $schematic->shapes(PartNumber)->first().points->map(.symbol)    // ['digit', 'digit', 'digit'] because each cell fell in the digit part

使用 rotated 时,正则表达式布局也会从后向前读取每一行,并且在网格中从下向上读取每一列。单词列表会按每个单元格一个单词的方式读取,因此 /\d+/ 作用于 ['ab', '12', '34'] 可以找到 ['12', '34']。

盖章遮罩:repeated

使用 repeated 时,遮罩如同曲奇模具:它会从左上角开始反复盖章,直到覆盖整个输入,位于右侧和底部边缘的副本会被截断。当每个副本的每个单元格都与第一个副本一致时(any 单元格不受约束),即视为匹配。匹配结果为第一个副本,copies 则指明盖了多少次章:

<type name="Checker" description="One black and one white tile, and the same two swapped below." extends="Mask">
  <field name="layout" default="```text
      #.
      .#
      ```" />
</type>

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

<echo value="$floor->shapes(Checker, repeated)->count()" /> <!-- 1 because the whole floor is a checkerboard -->
<echo value="$floor->shapes(Checker, repeated)->first().copies" /> <!-- 6 because 2 rows of 3 stamps cover it, the last row and column cut off -->
<echo value="'#..'->shapes(Checker, repeated)->count()" /> <!-- 0 because the third cell should be # like the first -->
/// One black and one white tile, and the same two swapped below.
type Checker extends Mask {
  layout: ```text
    #.
    .#
    ```
}

$floor = ```text
#.#.#
.#.#.
#.#.#
```

echo $floor->shapes(Checker, repeated)->count()            // 1 because the whole floor is a checkerboard
echo $floor->shapes(Checker, repeated)->first().copies     // 6 because 2 rows of 3 stamps cover it, the last row and column cut off
echo '#..'->shapes(Checker, repeated)->count()             // 0 because the third cell should be # like the first

正则表达式布局没有固定的大小,因此使用 repeated 时,它会先尝试最短的模具并返回能够匹配的最短结果:前 size 个单元格沿行盖章后必须恰好构成该行,并且正则表达式必须完整匹配这些单元格。它一次只读取一行,因此请每次只提供一行:

<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
  <field name="layout" default="/[roygbv]+/" />
</type>

<let name="printed" value="'rgbrgbrgbr'->shapes(Instructions, repeated)->first()" />
<echo value="$printed.points->map(.value)->join('')" /> <!-- 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr -->
<echo value="$printed.copies" /> <!-- 4 because the fourth rgb is cut off after its r -->
/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
  layout: /[roygbv]+/
}

$printed = 'rgbrgbrgbr'->shapes(Instructions, repeated)->first()
echo $printed.points->map(.value)->join('')   // 'rgb' because rgb, stamped and cut off, prints rgbrgbrgbr
echo $printed.copies                          // 4 because the fourth rgb is cut off after its r

可匹配任意内容的单元格:blank

输入有时会有损坏或未知的部分。blank: 用于指定可以匹配任意内容的单元格,可以是一个值('?')、一个正则表达式或一个 fn(cell)。空白单元格可以匹配任何符号,并且在使用 same 或 repeated 时不参与比较,因此各副本会相互填补空白:当另一副本已知某个点的值时,该点的 value 即为被填补后的值。blank: 应写在调用中而不是遮罩中,因为它描述的是输入,而不是形状:

<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
  <field name="layout" default="/[roygbv]+/" />
</type>

<let name="cutter" value="'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()" />
<echo value="$cutter.points->count()" /> <!-- 5 because no shorter cutter agrees with every colour that can be read -->
<echo value="$cutter.points->map(.value)->join('')" /> <!-- 'o?yv?' because the y comes from the second copy, and two cells are never read -->
<echo value="'???'->shapes(Instructions, repeated, blank: '?')->first().points->count()" /> <!-- 1 because a barcode of blanks fits one instruction -->
/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
  layout: /[roygbv]+/
}

$cutter = 'o??v???y'->shapes(Instructions, repeated, blank: '?')->first()
echo $cutter.points->count()                     // 5 because no shorter cutter agrees with every colour that can be read
echo $cutter.points->map(.value)->join('')       // 'o?yv?' because the y comes from the second copy, and two cells are never read
echo '???'->shapes(Instructions, repeated, blank: '?')->first().points->count()   // 1 because a barcode of blanks fits one instruction

内置形状同样支持 blank:,并且 of: 除了值或正则表达式之外也支持 fn(cell),因此这三者读取单元格的方式一致:$field->shapes(square, of: '#', blank: '?') 会将 ? 计为 #。

要在条形码列表的各行中查找某个形状,可以对各行进行映射:

<type name="Instructions" description="A printer's instructions: one or more colours, read along a row." extends="Mask">
  <field name="layout" default="/[roygbv]+/" />
</type>

<let name="barcodes">```text
    rgbrgbrgbr
    ?rv
    ??b?????
    ```</let>

<echo value="$barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())" />
<!-- 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b) -->
/// A printer's instructions: one or more colours, read along a row.
type Instructions extends Mask {
  layout: /[roygbv]+/
}

$barcodes = ```text
rgbrgbrgbr
?rv
??b?????
```

echo $barcodes->lines()->sum(fn(barcode) => $barcode->shapes(Instructions, repeated, blank: '?')->first().points->count())
// 6 because rgbrgbrgbr needs 3 instructions, ?rv needs 2 (vr) and ??b????? needs 1 (b)

遮罩包含 layout、symbols 及其自身的方法,使用 : 编写。编辑器和 kscript check 会报告编写有误的遮罩,并且大多数会给出修复建议:缺少或为空的布局,布局全部由 any 组成,图案中包含制表符,各层高度不一致,符号超过一个字符或被重复列出,null 应为 any,引号中的 'same' 应改为 same,symbols 与正则表达式布局并存,layout = 应为 layout:,对内置形状使用 repeated,将遮罩传给 ->find_all() 或 ->matches()(它们接受的是正则表达式),以及 like:(->shapes() 已不再接受)。布局中未使用的符号会给出警告(KS6026),将字符映射为其自身的符号同样会给出警告(KS6025),因为每个字符本就与自身匹配。

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

在编辑器中,遮罩是语言的一部分。extends ‸ 会提供 Mask,在 Mask 类型内部输入 layout 即可编写文本块;一旦有了文本块,symbols 会以布局中的一个字符和 any 的形式完整写出。在 symbols: { } 内部,自动补全会提供布局中尚未列出的字符;在某个键的冒号之后,则会提供 any、same、same(/…/)、值、正则表达式和 fn(cell)。在 layout: 之后,它会提供文本块和正则表达式。签名提示工具会在编写遮罩时显示 ->shapes(mask, rotated?, repeated?, blank?)。将鼠标悬停在布局的某个字符上,会显示该字符所匹配的内容以及布局中使用它的次数,并且每个字符会按其匹配内容着色:与自身匹配的字符或值(如文本)、正则表达式对应的颜色、fn 对应函数的颜色,而 any 则以注释的淡化颜色显示。

按序列工作

相乘: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']]

一种常见用法是检查每一对组合,例如查找两个价格之和等于某个总额的组合:

<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)。只有一个参数的函数仍会接收整个选取结果:

<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

由于所选项目依次填入参数,这样的函数无法同时获得索引:以两两配对为例,fn(first, second) 就是该配对的两个项目。

所有排列:permutations

->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 种排列),因此超过一百万个列表时会以 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() }"

你可以扩展 string、number(或 int 和 float)、bool、list、set、map、fn、date、email、password、handle、uuid 和 regex,也可以扩展包中的值,例如 file 或 response,以及你自己的 type,其方法中可通过 $this.name 访问 $this(即一条记录)及其字段。方法和其他 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/ 文件夹中的每个文件都会应用于项目中的每个脚本、测试和页面,无需导入。你可以按需拆分,例如每个类型一个文件:

文本
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"]。两个扩展文件为同一类型添加同名方法会报错,错误信息会同时指出两个文件。脚本自身的 extend(或导入文件中的)优先于项目中的定义。

编辑器只在扩展方法适用的范围内提供补全和检查:在既未声明、也未导入(或通过项目获得)->api_date() 的文件中,日期上的方法 @today()->api_date() 仍会被视为未知方法。悬停时会显示该方法的 /// 文档以及添加它的文件,跳转到定义则会打开该文件。