函数
<fn name="greet" params="who: string, greeting = 'Hello'">
<return value="$greeting + ', ' + $who + '!'" />
</fn>
<fn name="square" params="n: number" value="$n * $n" />
<echo>{ @greet('World') } { 4 |> @square() }</echo>
<do>@greet('Kyle')</do>
<spawn fn="background_job" />fn greet(who: string, greeting = 'Hello') {
return $greeting + ', ' + $who + '!'
}
fn square(n: number) => $n * $n
echo "{ @greet('World') } { 4 |> @square() }"
@greet('Kyle')
spawn(fn: @background_job)函数可以在声明之前调用、可以递归,也可以作为参数传递:@square 本身就是该函数。Lambda 同样是值,并以相同的简单方式声明其参数:$by_age = fn(a, b) => $a.age - $b.age。
简短的函数会对每个元素读取字段或调用方法。它以 . 或 -> 开头,代表当前元素,可用于任何需要函数的地方:
<let name="urgent" value="$orders->sort(by: .priority)->filter(.paid)" />
<let name="by_shop" value="$orders->group_by(.shop.name)" />
<let name="lines" value="$lines->map(->trim()->upper())" />$urgent = $orders->sort(by: .priority)->filter(.paid)
$by_shop = $orders->group_by(.shop.name)
$lines = $lines->map(->trim()->upper()).priority 等同于 fn(order) => $order.priority,->trim() 等同于 fn(line) => $line->trim()。简短的函数是由字段和方法调用组成的单个链式表达式。对于更复杂的情况,例如 $order.price > 10,请改写为 fn(order) => …。
块函数
当函数需要不止一个表达式时,请使用代码块代替 =>。该代码块包含语句,与 fn name() { } 的函数体相同,并由 return 给出函数的结果:
<let name="prices" value="[3, 7, 12]" />
<let name="with_tax">$prices->map(fn(price) {
$taxed = $price * 1.5 // 4.5 for the first price, because 3 * 1.5 is 4.5
return $taxed->round() // 5, because 4.5 rounds up
})</let>
<!-- $with_tax is [5, 11, 18]: the block ran once for each price -->$prices = [3, 7, 12]
$with_tax = $prices->map(fn(price) {
$taxed = $price * 1.5 // 4.5 for the first price, because 3 * 1.5 is 4.5
return $taxed->round() // 5, because 4.5 rounds up
})
// $with_tax is [5, 11, 18]: the block ran once for each price参数的类型由调用处推断,与 fn(price) => … 中的情况相同:这里 $price 是数字,因为 $prices 是数字列表,因此编辑器会在 $price-> 之后建议数字方法,并显示 with_tax: number[]。
代码块可以用 if 做判断,也可以用 return 提前退出:
<let name="scores" value="[42, 97, 61, 88]" />
<let name="passed">$scores->filter(fn(score) {
if $score < 60 {
return false // 42 is dropped here, because it is under 60
}
return $score % 2 == 0 // 97 and 61 are dropped, because they are odd
})</let>
<!-- $passed is [88] -->$scores = [42, 97, 61, 88]
$passed = $scores->filter(fn(score) {
if $score < 60 {
return false // 42 is dropped here, because it is under 60
}
return $score % 2 == 0 // 97 and 61 are dropped, because they are odd
})
// $passed is [88]带两个参数的函数(例如 ->reduce(fn(total, item), initial?))同样可以接受代码块:
<let name="basket" value="[{ name: 'apple', cost: 2 }, { name: 'melon', cost: 5 }]" />
<let name="total">$basket->reduce(fn(sum, item) {
return $sum + $item.cost // 2 after the apple, then 7, because the melon adds 5
}, 0)</let>
<!-- $total is 7 -->$basket = [{ name: 'apple', cost: 2 }, { name: 'melon', cost: 5 }]
$total = $basket->reduce(fn(sum, item) {
return $sum + $item.cost // 2 after the apple, then 7, because the melon adds 5
}, 0)
// $total is 7以 return 结束的代码块会返回 null,适用于 ->each() 这类只关心代码块所执行操作的场景。在其他场景中,调用会使用代码块的返回值,因此空的或从不返回值的代码块是错误的,无论在编辑器中、在 kscript check 中还是运行时都会报错:
<let name="words" value="['fig', 'kiwi']" />
<let name="longest">$words->common(1, by: fn(word) {
})</let>
<!-- Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives. -->$words = ['fig', 'kiwi']
$longest = $words->common(1, by: fn(word) {
})
// Error: This fn block is empty, so it gives null each time it is called, and 'by' uses what it gives.代码块可以读取并修改其周围的变量,它所创建的变量则只在代码块内部有效:
<let name="seen" value="0" />
<do>['x', 'y', 'z']->each(fn(letter) {
$seen = $seen + 1 // the outer $seen goes up, because the block changes the variable around it
$shout = $letter->upper() // $shout exists only inside the block
echo $shout // X, then Y, then Z, because the block runs once per letter
})</do>
<!-- $seen is 3 -->$seen = 0
['x', 'y', 'z']->each(fn(letter) {
$seen = $seen + 1 // the outer $seen goes up, because the block changes the variable around it
$shout = $letter->upper() // $shout exists only inside the block
echo $shout // X, then Y, then Z, because the block runs once per letter
})
// $seen is 3块函数与其他函数一样是一个值,因此可以保存在变量中并被调用:先写 $greet = fn(name) { … },再调用 $greet('Ada')。块函数可用于 .kscript 文件。XML 属性无法容纳语句,因此在那里应写成 fn(n) => value,或者声明一个 <fn> 并将其作为 @name 传递。数据库查询的条件(->where(fn(u) => $u.age >= 18))会被转换为 SQL,因此它必须保持为单个表达式。
声明为 any 的参数可以接受任何值。对其进行的方法调用会使用该值的实际类型。例如,$key->trim() 会去除字符串的首尾空白,对数字则会报错,并且在该类型存在自己的 trim() 时会调用它。对于字符串规范化,请写成 fn trim_key(key: string) => $key->trim()。这样编辑器便可推断出字符串的返回类型。
命名参数
任何调用都可以按任意顺序为参数命名:内置命令、方法、你自己定义的 fn 函数以及 Lambda 均可。
<echo>{ @known_folder(name: 'downloads') }</echo>
<echo>{ @greet(greeting: 'Hi', who: 'Kyle') }</echo>
<echo>{ @range(1, step: 2, end: 10) }</echo>
<echo>{ 'abc'->pad(char: '*', width: 6, start) }</echo>
<echo>{ @join_path(base: $folder, ['archive', $name]) }</echo>echo "{ @known_folder(name: 'downloads') }"
echo "{ @greet(greeting: 'Hi', who: 'Kyle') }"
echo "{ @range(1, step: 2, end: 10) }"
echo "{ 'abc'->pad(char: '*', width: 6, start) }"
echo "{ @join_path(base: $folder, ['archive', $name]) }"位置参数按顺序填充参数,每个 name: value 则填充同名的参数,因此你可以跳过中间的可选参数。写在命名参数之后的位置参数会填充第一个仍为空的参数,@join_path(base: $folder, [...]) 的读法即是如此。为不存在的参数命名,或为同一参数重复赋值,都会报错,并附带“你是否想要”的提示。编辑器会在 ( 或 , 之后补全参数名。
互斥组
部分参数是互斥的选项:一次调用只能传入其中之一。用 | 连接它们的名称:
<fn name="file" params="note_id: int, add|remove: string, notify: bool = true">
<let name="change" value="$add != null ? "Added { $add }" : "Removed { $remove }"" />
<let name="told" value="$notify ? ', and told its owner' : ''" />
<return value=""{ $change } on note { $note_id }{ $told }"" />
</fn>
<echo value="@file(4, add: 'plan.png')" />
<echo value="@file(4, remove: 'old.png', not notify)" />fn file(note_id: int, add|remove: string, notify: bool = true) {
$change = $add != null ? "Added { $add }" : "Removed { $remove }"
$told = $notify ? ', and told its owner' : ''
return "{ $change } on note { $note_id }{ $told }"
}
echo @file(4, add: 'plan.png')
echo @file(4, remove: 'old.png', not notify)@file(4, add: $a, remove: $b) 是错误的(“@file() 只接受 add: 或 remove:,不能两者都传”),@file(4) 同样是错误的(“需要 add: 或 remove:”)。kscript check 会在代码运行前同时报告这两种情况。组内成员始终需要命名,调用时未传入的成员在函数体中为 null。为其中某个成员传入 null(或 false)等同于未传入。
| 写法 | 含义 |
|---|---|
add|remove: file |
add 与 remove 两个文件中恰好一个。 |
at|after?: date |
至多一个:最后一个名称后的 ? 允许调用时两者都不传。 |
text: string | template: Template |
恰好一个,且各自有自己的类型。 |
(text: string | template: Template)? |
同样的含义,用方括号表示,其中 ? 表示至多一个。 |
当一个组的成员类型不同,而该组旁边还有其他参数时,需要使用方括号,以明确组的结束位置:fn send(to: email, (text: string | template: Template), at|after?: date)。任何组都允许加方括号。组内成员不能有自己的默认值。
内置命令也使用互斥组。@api() 接受 post:、put:、patch: 和 delete: 之一,作业的 ->dispatch() 接受 delay: 或 at:,二者不能同时使用。签名帮助会将一个组显示为一个位置,一旦写入了其中一个成员,补全便不再提供组内其他成员,而且编辑器会为一个组的名称使用同一种颜色。
标志
布尔类型的参数可以写成单独的词:recursive 将其设为真,not recursive 将其设为假,因此调用读起来像一句话。
<let name="all" value="@files($folder, pattern: '*.txt', recursive)" />
<echo>{ $data->convert(to: json, indented) }</echo>
<fn name="save" params="path: string, overwrite: bool = false">
<!-- … -->
</fn>
<do>@save('out.txt', overwrite)</do>$all = @files($folder, pattern: '*.txt', recursive)
echo "{ $data->convert(to: json, indented) }"
fn save(path: string, overwrite: bool = false) {
// …
}
@save('out.txt', overwrite)写成 overwrite: true 或 recursive: false 也可以,但编辑器会改为建议使用标志(KS6024),并提供将其改写为 overwrite 或 not recursive 的修复建议。
参数类型
每个实参都必须是其参数所接受的值。一条规则决定了这一点,编辑器、kscript check 和运行时都应用同一规则,因此它们会在代码运行前以相同的措辞报告同样的错误:
<let name="rolls" value="[4, 6, 6, 2]" />
<do>$rolls->common(1, least)</do> <!-- [2]: least on its own is true -->
<do>$rolls->common(1, not least)</do> <!-- [6]: not least is false -->
<do>$rolls->common(1, least: 'yes')</do> <!-- [2]: text that reads as true or false is converted -->
<do>$rolls->common('1')</do> <!-- [6]: text that reads as a number is converted -->
<do>$rolls->common(1, least: {})</do>
<!-- Error: The 'least' argument needs true or false, but this is a map. It is a flag: write least on its own for true, or not least for false. -->
<do>$rolls->common(fn() => 2)</do>
<!-- Error: The 'count' argument needs a number, but this is a function. -->
<do>$rolls->common(1, by: 3)</do>
<!-- Error: The 'by' argument needs a function, but this is a number. -->
<do>['fig']->union('fig')</do>
<!-- Error: The 'other' argument needs a list, but 'fig' is text. -->$rolls = [4, 6, 6, 2]
$rolls->common(1, least) // [2]: least on its own is true
$rolls->common(1, not least) // [6]: not least is false
$rolls->common(1, least: 'yes') // [2]: text that reads as true or false is converted
$rolls->common('1') // [6]: text that reads as a number is converted
$rolls->common(1, least: {})
// Error: The 'least' argument needs true or false, but this is a map. It is a flag: write least on its own for true, or not least for false.
$rolls->common(fn() => 2)
// Error: The 'count' argument needs a number, but this is a function.
$rolls->common(1, by: 3)
// Error: The 'by' argument needs a function, but this is a number.
['fig']->union('fig')
// Error: The 'other' argument needs a list, but 'fig' is text.| 参数接受 | 同时也接受 | 从不接受 |
|---|---|---|
文本(string) |
以文本形式写出的数字或真/假 | 列表、映射或函数 |
数字(number、int、float) |
可被读作数字的文本,例如 '3' |
其他文本、真/假、列表、映射或函数 |
真或假(bool) |
可被读作真或假的文本,例如 'yes' |
数字、列表、映射或函数 |
| 列表、映射或函数 | 其他任何值 |
你声明的函数对文本更为严格:声明为 string 的参数或结果只接受文本。数字或真/假在编辑器中、在 kscript check 中以及运行时都是错误,因此传入错误值的调用无法悄悄将其转换为文本。请将调用中写出的值用引号括起来,或用 ->to_string() 将数字转换为文本。编辑器会将这两种做法都作为快速修复提供。
<fn name="count_trees" params="input: string" value="$input->grid()->count()" />
<do>@count_trees(1)</do>
<!-- Error: The 'input' argument needs string, but this value is a number, not text. -->
<do>@count_trees('1')</do> <!-- fine: '1' is text -->
<let name="trees" value="3" />
<do>@count_trees($trees->to_string())</do> <!-- fine: the number 3, turned into the text '3' -->fn count_trees(input: string) => $input->grid()->count()
@count_trees(1)
// Error: The 'input' argument needs string, but this value is a number, not text.
@count_trees('1') // fine: '1' is text
$trees = 3
@count_trees($trees->to_string()) // fine: the number 3, turned into the text '3'{ } 始终是映射,即使它写在参数名后面的两行中,因此下一行的 least: { 和 } 是映射而不是代码块。编辑器会提供将 least: { } 替换为 least 的选项。
尾随逗号
列表中的项之间用逗号分隔。只有当列表每行写一项时,才允许在最后一项后加逗号,这样增加一项时只需改动一行。若在同一行的结束括号前加逗号,则在任何类型的列表中都是错误的:
<let>$label = fn(name,) => $name</let> <!-- Error: Nothing follows this comma. -->
<let>$sizes = [1, 2,]</let> <!-- Error, and the same for { size: 1, } and ->take(2,) -->
<set name="sizes">[
1,
2, // fine: the list is written one per line
]</set>$label = fn(name,) => $name // Error: Nothing follows this comma.
$sizes = [1, 2,] // Error, and the same for { size: 1, } and ->take(2,)
$sizes = [
1,
2, // fine: the list is written one per line
]枚举与常量
enum 用于声明一组命名值,const 用于声明一个不可更改的值。
<enum name="Size" values="small, medium, large" />
<const name="max_items" value="10" />
<fn name="pack" params="size: Size, gift: bool = false" value="'Packing ' + $size" />
<echo>{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }</echo>enum Size { small, medium, large }
const $max_items = 10
fn pack(size: Size, gift: bool = false) => 'Packing ' + $size
echo "{ @pack(.large) } { @pack(size: .small, gift) } { Size.medium }"长枚举可以每行放一个值,且不需要逗号,就像类型每行放一个字段一样。kscript fmt 会把能放进行宽的枚举放在同一行,较长的枚举则每行放一个值:
<enum name="Topping" values="mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos" />enum Topping {
mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos
}在已知类型的情况下,枚举的值前面要加一个前导点:.large 即 Size.large,因为 size 是 Size(参见下文的前导点)。若没有任何信息说明类型,则需完整书写:Size.medium。枚举的列表使用枚举值的数组:使用 fn pack_all(sizes: Size[]) 时,写作 @pack_all([.large, .small])。内置命令也有单词参数,这些单词直接书写,不加点:@known_folder(downloads) 接受 home、desktop、documents、downloads、music、pictures、videos、appdata 或 temp。Size 本身是一个从每个名称映射到其自身的映射,因此 'large' in Size 可用于检查某个值。顶层的 <const> 和 <enum> 声明会导出给导入该文件的脚本。
前导点: .name
以点号开头的名称是所在位置所期望的类型的成员。当周围的代码已经说明了类型时,可以省去写类型名称:
<enum name="NoteColor" values="yellow, pink, blue, red" />
<type name="Note">
<field name="text" type="string" />
<field name="color" type="NoteColor" default=".yellow" />
<fn name="label" value=".text->upper()" />
<fn name="urgent" value=".color == .red" />
<fn name="kind" returns="string" value="match .color {
.red => 'Urgent'
_ => 'Normal'
}" />
</type>
<fn name="paint" params="color: NoteColor" returns="string" value=""painted { $color }"" />
<let name="note" value="Note(text: 'milk', color: .pink)" />
<echo>{ $note->label() } { $note->kind() } { $note->urgent() } { @paint(color: .blue) }</echo>
<let name="people" value="[{ name: 'Ann', age: 31 }, { name: 'Bo', age: 25 }]" />
<echo value="$people->sort(by: .age)->map(.name)" />enum NoteColor { yellow, pink, blue, red }
type Note {
text: string
color: NoteColor = .yellow
fn label() => .text->upper()
fn urgent() => .color == .red
fn kind(): string => match .color {
.red => 'Urgent'
_ => 'Normal'
}
}
fn paint(color: NoteColor): string => "painted { $color }"
$note = Note(text: 'milk', color: .pink)
echo "{ $note->label() } { $note->kind() } { $note->urgent() } { @paint(color: .blue) }"
$people = [{ name: 'Ann', age: 31 }, { name: 'Bo', age: 25 }]
echo $people->sort(by: .age)->map(.name)点号的含义按以下顺序读取:
- 一个带类型的槽位。 参数、字段的默认值、比较、匹配分支、列表项,或接受枚举的带类型
fn的返回值:.pink即该枚举的值。接受函数的槽位(如->map(.name))会读取每个项目的该字段。 - 循环中的项,位于
for循环内。 在for account in $accounts { ... }中,.id的值为$account.id,.name = 'Ann'用于设置该项的字段。在嵌套循环中,同名的最内层项优先,因此内层循环的.label与外层循环的.id可以并列使用。while循环没有项,因此不会添加任何内容。 - 记录自身,在其自身的方法内。 在
type、model、extend或组件方法中,.text是记录自身的字段,.save()调用其自身的方法。.count += 1和.color = .red用于设置其字段。 - 这些都不是。
$c = .red是一个错误,.red needs a type here,快速修复会把它完整写出:NoteColor.red。
先尝试槽位。在方法内部,@paint(color: .red) 即为 NoteColor.red,即使记录中有名为 red 的字段也是如此。枚举中没有的名称属于记录自身,因此 fn current(): NoteColor => .color 返回记录的 color。两者都没有的名称则会报错。
循环的 item 位于 record 之前。在遍历带有 title 的行的方法中,.title 属于该行,而记录自身的则写作 $this.title;检查器会指出这一点并提供该修复方法。
<type name="Tag">
<field name="label" type="string" />
</type>
<type name="Row">
<field name="id" type="int" />
<field name="name" type="string" />
<field name="tags" type="Tag[]" default="[]" />
</type>
<let name="rows" type="Row[]" value="[Row(id: 1, name: 'Ann', tags: [Tag(label: 'new')])]" />
<for each="row" in="$rows">
<echo>{ .id } { .name->upper() }</echo>
<for each="tag" in=".tags">
<echo>{ .id } { .label }</echo>
</for>
</for>type Tag {
label: string
}
type Row {
id: int
name: string
tags: Tag[] = []
}
$rows: Row[] = [Row(id: 1, name: 'Ann', tags: [Tag(label: 'new')])]
for row in $rows {
echo "{ .id } { .name->upper() }"
for tag in .tags {
echo "{ .id } { .label }"
}
}在值的位置输入 . 时,会精确提示适合填入的内容:在有类型的位置提示枚举的值;在循环中提示循环项的字段(然后是外层循环的字段,最后是记录的字段);在方法中提示记录的字段和方法。将鼠标悬停在某个值上,会显示它所代表的含义,例如 NoteColor.pink。