Functions and closures

Functions are first-class values. XS supports default parameters, variadic args, closures, generators, and overloading by argument count.

Basics

scratch.xs

fn main() is auto-called if defined. In scripts without a main, the top-level code runs directly.

Default args and variadic

scratch.xs
scratch.xs

Closures

Closures capture variables by reference through an environment chain. Mutations inside the closure are visible to the outer scope.

scratch.xs
scratch.xs

Generators

Generator functions use fn* and yield to produce values lazily. They work with for..in loops.

scratch.xs

Overloading

Multiple functions with the same name are dispatched by argument count. First exact arity match wins.

scratch.xs

Functions defined later in a file can call functions defined earlier, and also vice versa (mutual recursion is fine):

scratch.xs

Function attributes

-- @test: marks the function as a test case (run by xs test)
@test
fn test_add() {
  assert_eq(1 + 2, 3)
}

-- @deprecated: warns callers at check time
@deprecated("use new_add() instead")
fn old_add(a, b) { return a + b }

Test functions produce no visible output when called directly. Run xs test to discover and execute them.

Generic type params

scratch.xs