Functions
<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)Functions can be called before they are declared, recurse, and be passed around: @square is the function itself. Lambdas are values too, and declare their parameters the same bare way: $by_age = fn(a, b) => $a.age - $b.age.
A lambda's parameter can have a type, written as a function's is. The argument is converted to it, or the script stops, as it would for a function:
<let name="area" value="fn(width: number, height: number) => $width * $height" />
<echo value="$area('3', 4)" /> <!-- 12: '3' reads as a number -->
<echo value="['a', 'b']->map(fn(s: string) => $s->upper())" />$area = fn(width: number, height: number) => $width * $height
echo $area('3', 4) // 12: '3' reads as a number
echo ['a', 'b']->map(fn(s: string) => $s->upper())A short function reads a field or calls a method on each item. It starts with . or ->, which stands for the item, and works anywhere a function goes:
<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 is fn(order) => $order.priority, and ->trim() is fn(line) => $line->trim(). A short function is one chain of fields and method calls. For anything more, such as $order.price > 10, write fn(order) => ….
The main function
A script can keep its work in a function called main. When the script is the one being run, main runs by itself once the top-level code has run, so the top-level code sets things up and main does the job:
<!-- greet.kscript, run with: kscript greet.kscript Ada Grace -->
<let name="greeting" value="'Hello'" /> <!-- the top-level code runs first -->
<fn name="main" params="args: list">
<!-- $args is ['Ada', 'Grace'], the words after the script's name -->
<for each="name" in="$args">
<echo>{ $greeting }, { $name }!</echo> <!-- Hello, Ada! then Hello, Grace! -->
</for>
</fn>// greet.kscript, run with: kscript greet.kscript Ada Grace
$greeting = 'Hello' // the top-level code runs first
fn main(args: list) {
// $args is ['Ada', 'Grace'], the words after the script's name
for name in $args {
echo "{ $greeting }, { $name }!" // Hello, Ada! then Hello, Grace!
}
}- Its parameter is optional.
fn main()runs the same way;fn main(args: list)gets the script's arguments, the same list as$args. A second parameter needs a default, since nothing else is passed:fn main(first, second)is an error (KS5004). - What it returns is the exit code. A whole number
mainreturns ends the script with that code, asexitdoes, so a shell or CI job can tell how it went. Anything else, or nothing, is exit code 0:
<fn name="main" params="args: list" returns="int">
<if $args->count() == 0>
<echo>Name a file to read.</echo>
<return value="2" /> <!-- exit code 2: the script wasn't given what it needs -->
</if>
<echo>Reading { $args[0] }</echo>
<return value="0" /> <!-- exit code 0: all went well -->
</fn>fn main(args: list): int {
if $args->count() == 0 {
echo 'Name a file to read.'
return 2 // exit code 2: the script wasn't given what it needs
}
echo "Reading { $args[0] }"
return 0 // exit code 0: all went well
}- Only the script being run.
mainbelongs to the script you run:kscript run,kscript greet.kscript, a compiled program, the debugger and the editor's Run command all call it. A script that is imported runs its top-level code but never itsmain, so a library can keep amainfor trying it out on its own. - Only at the top level. A
fn maininside another function, a type or a test file is an ordinary function. - Never unused. Nothing calls
main, sokscript checkand the editor never report it as unused (KS6002). They warn when the top-level code calls it too, because it would then run twice (KS5019); remove the call, as the quick fix does.
app.main_function in kscript.json gives it another name, for every script in the project:
{
"app": { "main_function": "start" } // fn start runs by itself; a fn main is then an ordinary function
}Block functions
When a function needs more than one expression, give it a block instead of =>. The block holds statements, just like the body of fn name() { }, and return gives the function's result:
<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 priceThe parameters get their types from the call, as they do in fn(price) => …: $price is a number here because $prices is a list of numbers, so the editor suggests number methods after $price-> and shows with_tax: number[].
A block can decide with if and leave early with 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]Functions that take two parameters, such as ->reduce(fn(total, item), initial?), take a block in the same way:
<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 7A block that ends without return gives null, which suits ->each(), where only what the block does matters. Everywhere else the call uses what the block gives, so a block that is empty or never returns a value is an error, in the editor, in kscript check and when it runs:
<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.The block can read and change the variables around it, and the variables it makes stay inside it:
<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 3A block function is a value like any other function, so it can be kept in a variable and called: $greet = fn(name) { … }, then $greet('Ada'). Block functions work in .kscript files. An XML attribute can't hold statements, so there you write fn(n) => value, or declare a <fn> and pass it as @name. A database query's condition (->where(fn(u) => $u.age >= 18)) is turned into SQL, so it must stay a single expression.
A parameter declared as any accepts any value. A method call on it uses the value's actual type. For example, $key->trim() trims a string, raises an error for a number, and calls the type's own trim() when one exists. Write fn trim_key(key: string) => $key->trim() for a string normalizer. The editor can then infer a string return type.
Named arguments
Any call can name its arguments, in any order: built-in commands, methods, your own fn functions and lambdas.
<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]) }"Positional arguments fill parameters in order, and each name: value fills the parameter of that name, so you can skip optional ones in between. A positional argument written after named ones fills the first parameter still empty, which is how @join_path(base: $folder, [...]) reads. Naming a parameter that doesn't exist, or giving one twice, is an error with a "did you mean" hint. The editor completes parameter names after ( or ,.
One of a group
Some parameters are alternatives: a call passes exactly one of them. Join their names with |:
<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) is an error ("@file() takes add: or remove:, not both"), and so is @file(4) ("needs add: or remove:"). kscript check reports both before the code runs. The members of a group are always named, and the ones a call doesn't pass are null in the body. Passing null (or false) for one counts as not passing it.
| Written | Means |
|---|---|
add|remove: file |
Exactly one of add and remove, both files. |
at|after?: date |
At most one: the ? after the last name lets a call pass neither. |
text: string | template: Template |
Exactly one, each with its own type. |
(text: string | template: Template)? |
The same in brackets, with ? for at most one. |
A group whose members have different types needs brackets when other parameters sit beside it, so it's clear where the group ends: fn send(to: email, (text: string | template: Template), at|after?: date). Brackets are allowed around any group. A member can't have a default of its own.
Built-in commands use groups too. @api() takes one of post:, put:, patch: and delete:, and a job's ->dispatch() takes delay: or at:, not both. Signature help shows a group as one slot, completion stops offering the other members once one is written, and the editor gives a group's names one colour.
Flags
A true/false parameter can be written as a bare word: recursive sets it to true and not recursive to false, so calls read like a sentence.
<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)Writing overwrite: true or recursive: false works too, but the editor suggests the flag instead (KS6024), with a fix that rewrites it as overwrite or not recursive.
Argument types
Each argument must be a value its parameter takes. One rule decides this, and the editor, kscript check and the run all apply it, so they report the same mistake in the same words before anything runs:
<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.| The parameter takes | It also takes | It never takes |
|---|---|---|
text (string) |
a number or true/false, written as text | a list, a map or a function |
a number (number, int, float) |
text that reads as a number, such as '3' |
other text, true/false, a list, a map or a function |
true or false (bool) |
text that reads as true or false, such as 'yes' |
a number, a list, a map or a function |
| a list, a map or a function | anything else |
A function you declare is stricter about text: a parameter or result declared as string takes text only. A number or true/false is an error in the editor, in kscript check and at run time, so a call that passes the wrong value can't quietly turn it into text. Put a value written in the call in quotes, or turn a number into text with ->to_string(). The editor offers both as quick fixes.
<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'A record of one declared type is checked against the type a parameter, a result or a typed variable declares. A record that lacks one of that type's required fields is an error before the script runs, as it is at run time:
<type name="Post">
<field name="title" type="string" />
</type>
<type name="Comment">
<field name="body" type="string" />
</type>
<fn name="headline" params="post: Post" value="$post.title->upper()" />
<echo value="@headline(Comment(body: 'First!'))" />
<!-- Error: The 'post' argument needs Post, but this value is a Comment, which has no title field. -->type Post {
title: string
}
type Comment {
body: string
}
fn headline(post: Post) => $post.title->upper()
echo @headline(Comment(body: 'First!'))
// Error: The 'post' argument needs Post, but this value is a Comment, which has no title field.A { } is always a map, even when it is written over two lines after an argument's name, so least: { and } on the next line is a map, not a block. The editor offers to replace least: { } with least.
Type parameters
A function that works the same way on any type names the type in angle brackets after its name and uses it in its parameters and result. A call fills it in from what it is given:
<fn name="first" generics="T" params="items: T[]" returns="T">
<return value="$items[0]" />
</fn>
<fn name="same" generics="T" params="a: T, b: T" returns="bool" value="$a == $b" />
<echo value="@first([3, 4])->round()" /> <!-- 3: @first() of a list of numbers is a number -->
<echo value="@first(['fig'])->upper()" /> <!-- FIG -->
<echo value="@same('a', 'b')" /> <!-- false -->fn first<T>(items: T[]): T {
return $items[0]
}
fn same<T>(a: T, b: T): bool => $a == $b
echo @first([3, 4])->round() // 3: @first() of a list of numbers is a number
echo @first(['fig'])->upper() // FIG
echo @same('a', 'b') // falseOne call gives each type parameter one type. @same(1, 'x') is an error in the editor, in kscript check and at run time, because a makes T a number and b is text. So is a result that isn't the type the call made T. Inside the function, T is any type, so $items[0] needs no check. Several type parameters are written with commas: fn pair<K, V>(key: K, value: V). In XML they go in the generics attribute: <fn name="first" generics="T" params="items: T[]" returns="T">.
Trailing commas
A comma goes between items. After the last item, a comma is allowed only when the list is written one item per line, so adding an item changes one line. Before the closing bracket on the same line it is an error, in every kind of list:
<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
]Enums and consts
enum declares a set of named values, and const a value that can't change.
<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 }"A long enum can hold one value per line, with no commas, the way a type holds one field per line. kscript fmt puts an enum that fits in the line width on one line, and a longer one one value per line:
<enum name="Topping" values="mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos" />enum Topping {
mozzarella
pepperoni
mushrooms
green_peppers
black_olives
pineapple
jalapenos
}Where the type is known, write an enum's value with a leading dot: .large is Size.large, because size is a Size (see A leading dot below). Where nothing says the type, write it in full: Size.medium. A list of an enum takes an array of them: with fn pack_all(sizes: Size[]), write @pack_all([.large, .small]). Built-in commands have word parameters too, and those words are written bare, without the dot: @known_folder(downloads) takes home, desktop, documents, downloads, music, pictures, videos, appdata or temp. Size itself is a map from each name to itself, so 'large' in Size checks a value. Top-level <const> and <enum> declarations are exported to scripts that import the file.
A leading dot: .name
A name that starts with a dot is a member of whatever the place it is written expects. It saves writing the type's name when the code around it already says it:
<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)What the dot means is read in this order:
- A typed slot. An argument, a field's default, a comparison, a match arm, a list item or a typed
fn's return that takes an enum:.pinkis that enum's value. A slot that takes a function, as->map(.name)does, reads that field of each item. - The item, inside a
forloop. Infor account in $accounts { ... },.idis$account.idand.name = 'Ann'sets the item's field. In nested loops the innermost item that has the name wins, so the inner loop's.labeland the outer loop's.idcan sit side by side. Awhileloop has no item, so it adds nothing. - The record, inside its own methods. In a
type,model,extendor component method,.textis the record's own field and.save()calls its own method..count += 1and.color = .redset its fields. - None of these.
$c = .redis an error,.red needs a type here, and the quick fix writes it in full:NoteColor.red.
The slot is tried first. Inside a method, @paint(color: .red) is NoteColor.red even if the record has a field called red. A name the enum doesn't have is the record's own, so fn current(): NoteColor => .color returns the record's color. A name neither has is an error.
A loop's item comes before the record. In a method that loops over rows that have a title, .title is the row's, and the record's own is written $this.title; the checker says so and offers that fix.
<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 }"
}
}Typing . where a value goes suggests exactly what fits: the enum's values in a typed slot, the loop item's fields (then the outer loops' and the record's) inside a loop, or the record's fields and methods inside a method. Hovering a value shows what it stands for, such as NoteColor.pink.