Korr

Language guide

Docs index

This is the complete reference for Korr’s syntax and semantics.

Contents: Layout | Variables | Types | Numbers | Strings | Arrays | Maps | Ranges & slicing | Operators | Conditions | Loops | match | Functions | Structs | Enums | Errors | Modules | Type annotations | Keywords


1. Layout and comments

// line comment
/* block
   comment */

if true
    print("blocks are indented by 4 spaces")
    print("same block")
print("back at the top level")
let names = ["  ana ", "BUDI", "sari"]
let clean = names
    .map(fn(n) => n.trim().capitalize())
    .sort()

2. Variables and constants

let count = 0          // variable
count = count + 1      // change it
count += 1             // compound: += -= *= /= %=

const PI = 3.14159     // constant: reassigning is a compile-time error

Destructuring:

let [first, second, ...rest] = [1, 2, 3, 4]      // rest == [3, 4]
let { name, age: years } = { name: "Ana", age: 20 }

An array pattern without ...rest must match the length exactly.

3. Types

Type Examples type(x)
null null "null"
bool true, false "bool"
int 42, -7, 1_000_000, 0xff, 0b1010, 0o17 "int"
float 3.14, 1e3, 2.5e-4 "float"
str "text", 'raw', """multi-line""" "str"
html html"<b>{name}</b>" "html"
array [1, "two", 3.0] "array"
map { name: "Ana", "key with space": 1 } "map"
fn fn(x) => x + 1, named functions, built-ins "fn"
struct instance User("Ana") the struct name, e.g. "User"
range 0..10, 1..=5 "range"
error error("message", "Kind") "error"

Truthiness (used by if, while, and, or, not): null, false, 0, 0.0, "", [], {} and empty ranges are falsy. Everything else is truthy.

Equality is structural: [1, 2] == [1, 2] and { a: 1 } == { a: 1 } are true; 1 == 1.0 is true. Values of different types are never equal (1 == "1" is false).

Conversions are always explicit: str(x), int(x), float(x), bool(x). int("abc") raises ValueError; int("abc", 0) returns the default 0 instead.

4. Numbers

print(7 / 2)        // 3.5   ('/' always gives a float)
print(math.div(7, 2))  // 3  (floor division for ints)
print(7 % 3)        // 1     (remainder; the sign follows the left side)
print(2 ** 10)      // 1024  (power; right-associative, -2 ** 2 == -4)
print(0.1 + 0.2)    // 0.30000000000000004
print(3.14159.round(2), 2.7.floor(), (-5).abs(), 9.5.fixed(2))

5. Strings

let name = "Korr"
let s1 = "Hello, {name}!"            // interpolation with {expression}
let s2 = "1 + 1 = {1 + 1}"
let s3 = "literal braces: "  //  gives }
let s4 = 'raw: no {interpolation}, no escapes: C:\Users\korr'
let s5 = "tab\t newline\n quote\" unicode \u{1F600}"

Multi-line strings use triple quotes and are automatically de-indented, so they can sit nicely inside indented code:

fn email(name)
    return """
        Hi {name},

        Thanks for signing up!
        """

The first newline and the common indentation are removed. '''...''' is the raw version.

HTML templates: prefix a double-quoted string with html and every {value} is HTML-escaped automatically:

let comment = "<script>alert('x')</script>"
let safe = html"<p>{comment}</p>"   // <p>&lt;script&gt;...</p>
let items = [html"<li>{x}</li>" for x in ["a", "b"]]
let list = html"<ul>{items}</ul>"   // arrays of html are joined, not re-escaped

html.raw(text) marks trusted HTML that should not be escaped. See Full-stack web.

String methods (upper, split, replace, …) are listed in the standard library.

6. Arrays

let xs = [3, 1, 2]
xs.push(4)                       // add to the end
print(xs[0], xs[-1], len(xs))    // 3 4 4
xs[0] = 10                       // replace
print(xs.sort(), xs)             // sort() returns a NEW array: [1, 2, 4, 10] [10, 1, 2, 4]
print([...xs, 5], [0] * 3, [1] + [2])
print(2 in xs, 9 not in xs)

Comprehensions (from Python):

let squares = [n * n for n in 1..=5]                 // [1, 4, 9, 16, 25]
let evens = [n for n in 0..20 if n % 2 == 0]
let labels = ["{i}: {v}" for i, v in ["a", "b"]]     // index, value
let keys = [k for k, v in { a: 1, b: 2 } if v > 1]   // ["b"]

7. Maps

Maps are ordered key/value collections with string keys (like JavaScript objects, PHP associative arrays and Python dicts).

let user = {
    name: "Ana",
    "favourite colour": "green",   // quoted keys may contain spaces
    age: 20,
}
print(user.name, user["age"], user.missing)   // Ana 20 null
user.city = "Bandung"            // add or change
user["zip"] = "40111"
let key = "role"
let copy = { ...user, [key]: "admin" }       // spread and computed keys
let x = 1
let y = 2
let point = { x, y }                          // shorthand for { x: x, y: y }
print("city" in user, user.keys(), len(user))

8. Ranges and slicing

for i in 0..5           // 0, 1, 2, 3, 4      (end excluded)
    print(i)
for i in 1..=5          // 1, 2, 3, 4, 5      (end included)
    print(i)

let xs = [10, 20, 30, 40, 50]
print(xs[1..3], xs[2..], xs[..2], xs[-2..])   // [20, 30] [30, 40, 50] [10, 20] [40, 50]
print("Korr lang"[0..4])                      // Korr
print(3 in 0..10, (0..5).to_array(), (1..4).map(fn(n) => n * n))
print(range(0, 10, 3))                        // [0, 3, 6, 9]: with a step

Slices are clamped (never an error) and always return copies.

9. Operators

From lowest to highest precedence:

Operator Meaning
c ? a : b ternary
x \|> f(y) pipe: same as f(x, y)
a ?? b b if a is null, else a
a or b a if truthy, else b
a and b a if falsy, else b
not a boolean negation
== != < <= > >= in not in comparison and membership
a..b a..=b ranges
+ - addition / subtraction / concatenation
* / % multiplication / division / remainder
-x negation
** power
f(x) x.y x?.y x[i] x?.[i] call, field, optional field, index
let config = { db: null }
let host = config.db?.host ?? "localhost"   // optional chaining + default
let label = len("items") > 3 ? "many" : "few"
let name = null or "anonymous"              // 'or' returns the first truthy value
let slug = "  Hello World " |> slugify()    // pipe
fn slugify(s) => s.trim().lower().replace(" ", "-")

10. Conditions

let temperature = 31
if temperature > 30
    print("hot")
else if temperature > 20
    print("warm")
else
    print("cold")

if is a statement. For an expression use cond ? a : b or match.

11. Loops

for fruit in ["apple", "mango"]          // values
    print(fruit)
for i, fruit in ["apple", "mango"]       // index and value
    print(i, fruit)
for key, value in { a: 1, b: 2 }         // map: key and value (one variable = keys)
    print(key, value)
for ch in "hey"                          // characters
    print(ch)

let n = 0
while n < 3
    n += 1

for i in 0..100
    if i % 2 == 0
        continue        // next iteration
    if i > 7
        break           // leave the loop
    print(i)

for i in a..b with a literal range is optimised and never allocates.

12. Pattern matching with match

match is an expression: it returns the value of the arm that matched.

fn describe(value)
    return match value
        0 => "zero"
        1 | 2 | 3 => "small"                 // alternatives
        4..=9 => "medium"                    // ranges (.. or ..=)
        "admin" => "a string"
        null => "nothing"
        [first, ...rest] => "array starting with {first}"   // array patterns
        n if type(n) == "int" and n < 0 => "negative"       // binding + guard
        _ => "something else"                // wildcard
let status = 404
match status
    200 => print("ok")
    404 =>
        print("not found")
        print("check the URL")
    _ => print("status {status}")

13. Functions

fn add(a, b)
    return a + b

fn square(x) => x * x                 // one-expression form

fn greet(name, greeting = "Hello")    // default values
    return "{greeting}, {name}!"

fn total(...prices)                   // rest parameter collects extra arguments
    return prices.sum()

print(add(1, 2), square(4), greet("Ana"), total(1, 2, 3))
print(greet(greeting: "Hi", name: "Budi"))   // named arguments, any order
print(total(...[5, 5]))                       // spread an array into arguments

Lambdas and closures:

let double = fn(x) => x * 2
let numbers = [1, 2, 3].map(fn(n) => n + 1)

fn make_counter()
    let count = 0
    return fn()
        count += 1
        return count

let next = make_counter()
next()
print(next())     // 2 (closures capture variables by reference)

A lambda with a block body can also be passed as an argument: end the line with fn(params), indent the body, and close the call on the next line at the original indentation (or right after the last statement):

let app = http.app()
app.get("/users/:id", fn(req)
    let id = int(req.params.id, 0)
    if id == 0
        return http.json({ error: "bad id" }, 400)
    return { id }
)

let items = [{ name: "Tea", price: 5000 }, { name: "Coffee", price: 12500 }]
let labels = items.map(fn(item)
    let price = item.price.fixed(0)
    return "{item.name}: Rp{price}")
print(labels)

// to pass more arguments after a block lambda, start the next line with them:
let total = [1, 2, 3].reduce(fn(acc, n)
    return acc + n * 2
, 0)

14. Structs and methods

Structs (from Rust) are named records with optional types and defaults. Methods go in an impl block; a method whose first parameter is self is called on an instance, otherwise it is a static function on the struct.

struct User
    name: str
    email: str
    age: int = 0
    roles: array = []

impl User
    fn is_adult(self) => self.age >= 18

    fn add_role(self, role)
        self.roles.push(role)

    fn guest()                         // static: User.guest()
        return User("Guest", "guest@example.com")

let ana = User("Ana", "ana@example.com", 20)         // positional
let budi = User(name: "Budi", email: "b@example.com")  // named, age defaults to 0
ana.add_role("admin")
print(ana.is_adult(), budi.age, User.guest().name)
print(ana)            // User { name: "Ana", email: "ana@example.com", age: 20, roles: ["admin"] }

15. Enums

An enum is a type with a fixed set of variants. A variant can carry data, like a small struct:

enum Shape
    Circle(r: float)
    Rect(w: float, h: float)
    Empty

let a = Shape.Circle(2.0)
let b = Shape.Rect(w: 3.0, h: 4.0)     // named fields work too
let c = Shape.Empty                     // a variant without data is a value

print(a)            // Shape.Circle(r: 2.0)
print(type(a))      // Shape

Take variants apart with match. The fields are matched by position:

// no-check
fn area(s: Shape) -> float
    return match s
        Shape.Circle(r) => 3.14 * r * r
        Shape.Rect(w, h) => w * h
        Shape.Empty => 0.0

Korr checks enums before the program runs:

Arms can use guards (Shape.Circle(r) if r > 10 => ...), _ for fields you do not need (Shape.Circle(_)), a variant without parentheses to match any of its values (Shape.Rect), and | (Shape.Rect | Shape.Empty => ...).

Methods work like on structs: impl Shape adds methods (with self) to every variant, and functions without self are called on the enum:

// no-check
impl Shape
    fn area(self) -> float
        return match self
            Shape.Circle(r) => 3.14 * r * r
            Shape.Rect(w, h) => w * h
            Shape.Empty => 0.0

    fn square(side: float) -> Shape
        return Shape.Rect(side, side)

print(Shape.square(2.0).area())   // 4.0

Enum values compare by variant and fields (Shape.Empty == Shape.Empty), work as type annotations (fn draw(s: Shape)), and json.encode writes the variant name: {"variant":"Circle","r":2.0}.

16. Errors

fn load(path)
    if not fs.exists(path)
        throw error("No such file: {path}", "NotFound")   // custom kind
    return fs.read(path)

try
    let text = load("settings.txt")
catch err
    print(err.kind, err.message, err.line)   // NotFound No such file: settings.txt 3
finally
    print("always runs")

Handle by kind with match:

try
    risky()
catch err
    match err.kind
        "NotFound" => print("missing")
        _ => throw err          // re-throw what you cannot handle

fn risky()
    throw error("gone", "NotFound")

17. Modules

Every .krr file is a module. Import with a relative path:

// no-check
import "./lib/money.krr" as money        // explicit alias
import "./utils.krr"                     // alias defaults to the file name: utils

print(money.format(1500))
fn create_app()
    let app = http.app()
    app.get("/", fn(req) => "hi")
    return app

if os.is_main()
    create_app().listen(8080)

18. Type annotations

Annotations are optional and checked at runtime: a wrong type is a TypeError naming the parameter, field or variable.

fn area(width: num, height: num) -> float
    return float(width * height)

let port: int = 8080
port = 9000            // still must be an int

fn find(id: int) -> ?str   // ?T means "T or null"
    return id == 1 ? "Ana" : null
Annotation Accepts
any anything
int, float, num int; int or float; int or float
str, bool, array, map, fn, null that type (str also accepts html)
User (a struct name) instances of that struct
error, html, range those built-in types
?T T or null

19. Keywords

let const fn return if else while for in break continue match struct impl enum try catch finally throw import as true false null and or not

Special names: self (first parameter of methods), _ (wildcard pattern), __dir__, __file__.


Previous: Getting started Docs index Next: Standard library