值与方法
值包括字符串、数字、布尔值、列表、映射、日期、函数和 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) // truenow 取自计算机时钟,因此在测试中 @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="'{"id": 1}'" />
<let name="signature" value="$body->hmac('whsec_test')" />
<echo value="@secure_equals($signature, $body->hmac('whsec_test'))" /> <!-- true -->$body = '{"id": 1}'
$signature = $body->hmac('whsec_test')
echo @secure_equals($signature, $body->hmac('whsec_test')) // true->md5()、->sha1()、->sha256()和->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 mostby:决定什么算作相同的项目。这里'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' }在格式之间转换: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="'{"fruit": "apple", "count": 3}'->convert(from: json)" />
<echo value="$order.count" /> <!-- 3 because the json text is now a map with a count key -->
<let name="settings">```yaml
theme: dark
size: 12
```</let>
<echo value="$settings->convert(from: yaml).size" /> <!-- 12 because the yaml is read into a map -->$order = '{"fruit": "apple", "count": 3}'->convert(from: json)
echo $order.count // 3 because the json text is now a map with a count key
$settings = ```yaml
theme: dark
size: 12
```
echo $settings->convert(from: yaml).size // 12 because the yaml is read into a mapCSV 默认包含标题行,用于为每行的键命名。当每一行都是数据时,写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="'{"fruit": "apple"}'->from(type: json)" />
<echo value="$order.fruit" /> <!-- 'apple' because ->from(type: json) is ->convert(from: json) -->
<echo value="[{ fruit: 'plum' }]->to(type: json)" /> <!-- [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json) -->$order = '{"fruit": "apple"}'->from(type: json)
echo $order.fruit // 'apple' because ->from(type: json) is ->convert(from: json)
echo [{ fruit: 'plum' }]->to(type: json) // [{"fruit":"plum"}] because ->to(type: json) is ->convert(to: json)->convert()是改变格式的唯一方式,因此旧的一格式一方法写法(->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 rowsrow:选取一行,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)
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.
要查找由 # 组成的实心 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 1symbols is only for the characters that mean something other than themselves. It maps a character to what it matches: a value (t: 'taken') matches a cell that holds it, a regex (/[#@]/) a cell whose text fits, a fn(cell) a cell it gives true for, and any a cell that isn't part of the shape. An any cell can hold anything, can hang over the edge of the input, and is left out of the match's points. To find four trees at the corners of a three-by-three square, with anything between them:
<type name="Corners" description="Trees at the four corners of a 3x3 square, anything between." extends="Mask">
<field name="layout" default="```text
#.#
...
#.#
```" />
<field name="symbols" default="{ '.': any }" />
</type>
<let name="orchard">```text
#.#.#
.#...
#.#.#
```</let>
<echo value="$orchard->shapes(Corners)->count()" /> <!-- 2 because the corners fit at columns 0-2 and at columns 2-4 -->
<echo value="$orchard->shapes(Corners)->first().points->map(.symbol)" />
<!-- ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the middle -->/// Trees at the four corners of a 3x3 square, anything between.
type Corners extends Mask {
layout: ```text
#.#
...
#.#
```
symbols: { '.': any }
}
$orchard = ```text
#.#.#
.#...
#.#.#
```
echo $orchard->shapes(Corners)->count() // 2 because the corners fit at columns 0-2 and at columns 2-4
echo $orchard->shapes(Corners)->first().points->map(.symbol)
// ['#', '#', '#', '#'] because . is any, so its cells aren't part of the match, even the # in the 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 countA mask holds layout, symbols and its own methods, written with :. The editor and kscript check report a mask written wrong, most with a fix: a missing or empty layout, a layout that is all any, a tab in the picture, layers of different heights, a symbol that is more than one character or is listed twice, null for any, layout = for layout:, and like:, which ->shapes() no longer takes. A symbol the layout doesn't use is a warning (KS6026), and so is one that maps a character to itself (KS6025), since every character already matches itself:
<type name="Block" extends="Mask">
<field name="layout" default="```text
##
```" />
<field name="symbols" default="{ '#': '#' }" /> <!-- the warning: '#' already matches '#'. -->
</type>type Block extends Mask {
layout: ```text
##
```
symbols: { '#': '#' } // the warning: '#' already matches '#'.
}In the editor, a mask is part of the language. extends ‸ offers Mask, and inside a Mask type, typing layout writes the text block; once it has one, symbols comes written out with a character of the layout and any. Inside symbols: { }, completion offers the layout's characters not yet listed. Hovering a character of the layout says what it matches and how often the layout uses it, and each character is coloured by what it matches: itself or a value like text, a regex like a regex, a fn like a function, and any dimmed like a comment.
按序列工作
相乘: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() }"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/ 文件夹中的每个文件都会应用于项目中的每个脚本、测试和页面,无需导入。你可以按需拆分,例如每个类型一个文件:
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() 仍会被视为未知方法。悬停时会显示该方法的 /// 文档以及添加它的文件,跳转到定义则会打开该文件。