` | Print the detailed explanation for an error code (e.g. `E0100`) and exit |
| `--version` | Print the compiler version and exit |
## yona (REPL)
`yona` is an interactive compile-and-run loop: each line you type is compiled to a temporary native executable, run, and its output printed.
```bash
$ yona
Yona REPL (type expressions, Ctrl-D to exit)
yona> 1 + 2
3
```
- Exit with `Ctrl-D`, `:q`, or `:quit`.
- The REPL honors `YONAC_CC`, `YONAC_LINKER_MODE`, and `YONAC_REQUIRE_INPROCESS_LLD`, and discovers the runtime from the same distribution roots as `yonac` (including `YONA_HOME`).
## Environment variables
| Variable | Effect |
|----------|--------|
| `YONA_HOME` | Additional Yona distribution root; searched for `lib/` (modules, `Prelude`) and packaged runtime objects |
| `YONA_PATH` | Extra module search directories (`Prelude.yonai` and `import … from …`). Separated by `:` on Unix and `;` on Windows. Needed when compiling from a directory that has no cwd-relative `lib/` |
| `YONAC_CC` | C compiler driver used to compile the runtime from source and to drive external linking (default: `cc` on Unix, `clang` on Windows) |
| `YONAC_LINKER_MODE` | Default for `--linker-mode` (`auto`, `bundled`, `system`, `inprocess`) when the flag is not given |
| `YONAC_REQUIRE_INPROCESS_LLD` | When set to `1`/`true`/`yes`/`on`, make a failed or unavailable in-process LLD link a hard error instead of falling back to the external linker |
| `YONA_COMPILE_GPU_VULKAN` | When set to `1` together with `VULKAN_SDK`, compile the runtime from source with Vulkan GPU support enabled; leave unset for the default CPU-only runtime |
## Common workflows
Compile a file to an executable and run it:
```bash
yonac hello.yona -o hello
./hello
```
Evaluate an expression directly:
```bash
yonac -e "1 + 2" -o calc
./calc
```
Inspect the generated LLVM IR:
```bash
yonac --emit-ir -e "import foldl from Std\List in foldl (\acc x -> acc + x) 0 [1, 2, 3]"
```
Get a detailed explanation for an error code:
```bash
yonac --explain E0100
```
Compile a module (producing `Geometry.o` and `Geometry.yonai`), then a program that imports it:
```bash
yonac Geometry.yona
yonac -I . main.yona -o app
```
Build with warnings as errors and debug info:
```bash
yonac --Wall --Werror -g main.yona -o app
```
Audit GPU-acceleratable call sites in a module, with inferred types:
```bash
yonac --emit-accelerator-report --emit-accelerator-report-with-types Stats.yona -I lib
```
---
# Error codes
Source: https://yona-lang.org/reference/error-codes/
Every compiler error includes a code like `[E0100]`. Run `yonac --explain E0100` to see a detailed explanation with examples for any code on this page. See the [Compiler CLI](/reference/cli/) reference for warning-control flags.
## Type errors (E01xx)
### E0100 — Type mismatch
Two types that should be compatible are not.
```yona
# Error: Int and String cannot be unified
1 + "hello"
# Fix: ensure both operands have the same type
1 + 2
```
Common causes:
- Operator applied to incompatible types (`Int + String`)
- If branches return different types (`if true then 1 else "no"`)
- Function called with the wrong argument type
- Sequence with mixed element types (`[1, "two", 3]`)
### E0101 — Infinite type
A type variable would need to contain itself (occurs check failure). This happens when an expression's type depends on itself circularly.
```yona
# Error: f's type would contain itself
let f x = f in f
```
**Fix:** break the self-reference; a function cannot be its own return type.
### E0102 — Tuple size mismatch
A tuple pattern has a different number of elements than the tuple being matched.
```yona
# Error: 3-tuple matched against 2-tuple pattern
case (1, 2, 3) of (a, b) -> a end
# Fix: match all elements
case (1, 2, 3) of (a, b, c) -> a end
```
### E0103 — Undefined variable
A variable is used but not defined in the current scope. The compiler suggests similar names when a close match exists:
```
error: undefined variable 'lenght'; did you mean 'length'? [E0103]
```
```yona
# Variables are only visible within their defining scope
let x = 42 in x # OK
x # Error: x is not in scope
```
**Fix:** correct the spelling or bind the variable before use.
### E0104 — Undefined function
A function is called but has not been defined or imported.
```
error: undefined function 'prnt'; did you mean 'print'? [E0104]
```
**Fix:** correct the typo or add the missing import.
### E0105 — No trait instance
A trait method is called on a type that doesn't implement the trait.
```yona
# Error: no instance for 'Num String'
abs "hello"
# Fix: use a type that has a Num instance
abs (-42)
```
### E0106 — Missing trait instances
A trait is used but no instances have been registered for it at all. This usually means the trait definition is missing or not imported.
**Fix:** define or import the trait and at least one instance.
## Effect errors (E02xx)
See [effects](/learn/effects/) for the effect system itself.
### E0200 — Unhandled effect operation
A `perform` calls an effect operation, but no `handle ... with` block in scope provides a handler.
```yona
# Error: no handler for State.get
perform State.get ()
# Fix: wrap in a handle block
handle
perform State.get ()
with
State.get () resume -> resume 42
return val -> val
end
```
### E0201 — Effect argument count mismatch
A `perform` call passes the wrong number of arguments to an effect operation.
```yona
# Effect declares: put : s -> ()
# Error: put expects 1 argument, got 0
perform State.put
# Fix: pass the required argument
perform State.put 42
```
### E0202 — Unhandled effect at call site
A function whose type includes latent effects (`!{Effect.op}`) is applied where those operations are not covered by a surrounding `handle ... with`. The primary diagnostic points at the introducing `perform`; a note marks the call that lets the effect escape.
```yona
# f : a -> !{State.get} Int
let f = (\x -> perform State.get ()) in
f 0 # Error: points at `perform State.get`
# Fix: handle the effect at the use site
handle f 0 with
State.get () resume -> resume 7
end
```
A direct `perform` without a handler still warns via `-Wunhandled-effect`.
## Parse errors (E03xx)
### E0300 — Unexpected token
The parser encountered a token that doesn't fit the expected syntax. Common causes:
- Missing closing bracket, paren, or `end` keyword
- Extra comma or semicolon
- Reserved word used as an identifier
### E0301 — Invalid syntax
The source code doesn't match any valid Yona syntax. Check expression structure and keyword spelling against the [language specification](/reference/specification/).
### E0302 — Invalid pattern
A pattern in a case expression or function parameter is malformed. Valid pattern forms:
```yona
42 # integer literal
"hello" # string literal
:ok # symbol
x # variable binding
_ # wildcard
(a, b) # tuple
[h|t] # head-tail (list)
[] # empty list
Some x # constructor
(n : Int) # typed (sum type)
p1 | p2 # or-pattern
```
## Codegen errors (E04xx)
### E0400 — Failed to emit object file
LLVM could not produce an object file. This is usually an internal compiler error.
### E0401 — Linking failed
The system linker failed to produce an executable. Common causes:
- Missing runtime library (`compiled_runtime.o`)
- Undefined symbols from missing module imports
- System linker not installed
**Fix:** check that the toolchain is installed and imported modules have been compiled; see the [Compiler CLI](/reference/cli/) reference for `YONAC_CC` and `--linker-mode`.
### E0402 — Unsupported expression
The codegen encountered an AST node it cannot compile. This may indicate a language feature that is not yet implemented.
### E0403 — Unknown field
A field access or update refers to a field name that doesn't exist on the ADT.
```yona
type Person = Person { name : String, age : Int }
p.email # Error: 'email' is not a field of Person
p.name # OK
```
### E0404 — Pipe requires function
The pipe operator (`|>` or `<|`) requires a function on the receiving side.
```yona
# Error: 42 is not a function
"hello" |> 42
# Fix: pipe into a function
"hello" |> length
```
## Refinement errors (E05xx)
### E0500 — Refinement predicate not satisfied
A function expects a refined type, but the compiler cannot prove that the argument satisfies the refinement predicate.
```yona
type NonEmpty a = { xs : [a] | length xs > 0 }
head : NonEmpty a -> a
# Error: cannot prove 'someList' is non-empty
head someList
# Fix: establish the fact via pattern matching
case someList of
[h|t] -> head someList # OK: [h|t] proves non-empty
[] -> defaultValue
end
```
Passing a literal that obviously satisfies the predicate (e.g. `head [1, 2, 3]`) also works, as does a pattern match or comparison that proves an integer refinement such as `{ n : Int | n > 0 && n < 65536 }`.
## Linearity errors (E06xx)
These are produced by the linearity checker for `Linear` values (see the [Prelude](/reference/prelude/)).
### E0600 — Use after consume
A linear value was used after it was already consumed by a pattern match or function call.
```yona
let conn = Linear (tcpConnect host port) in
case conn of Linear fd -> close fd end # conn consumed
send conn "hello" # Error: already consumed
```
**Fix:** use the value before consuming it — do all work inside the case arm that unwraps it.
### E0601 — Branch inconsistency
A linear value is consumed in one branch of an if/case expression but not the other. Both branches must consume the same linear values.
```yona
# Error: conn consumed in then-branch but not else-branch
if ready then
case conn of Linear fd -> close fd end
else
() # conn still live here
```
**Fix:** consume the value in every branch (e.g. close it in the else branch too).
### E0602 — Resource leak
A linear value went out of scope without being consumed. This likely means a resource (file, socket, process) is leaked.
```yona
let conn = Linear (tcpConnect host port) in
42 # Error: conn never consumed
```
**Fix:** consume the value via pattern match before the end of its scope.
### E0603 — Invalid `@borrow`
`@borrow` marks a parameter as read-only for the function body: it must not be returned, stored in a collection literal, captured by a nested lambda, or used as a case scrutinee (head/tail consumes the sequence). It is only supported on simple identifier parameters.
```yona
# Error: borrowed parameter is returned
let f @borrow s = s in f
```
**Fix:** remove `@borrow`, or change the body so the parameter is only read.
## Accelerator errors (E07xx)
### E0700 — Unlowerable accelerator lambda
Only reported under `yonac --strict-accelerator`, which requires `Std\IntArray` / `Std\FloatArray` `map` / `filter` / `foldl` lambdas to match the fixed [Std\GPU](/stdlib/gpu/) kernel library (`x + k`, `x * k`, `x > k`, sum, float scale). Arbitrary lambdas such as `\x -> x * x` are not compiled to SPIR-V; without the flag they stay on the correct host closure path, while with it they are a hard error so GPU expectations cannot silently diverge from the fixed-kernel ABI.
**Fix:** rewrite the lambda as a fixed kernel (e.g. `map (\x -> x + 1)`, explicit `mapGPU`), or drop `--strict-accelerator` to keep the host path.
## Warning flags
Warnings are controlled via `--Wall`, `--Wextra`, `-w`, and `--Werror` (see the [Compiler CLI](/reference/cli/)).
| Flag | Name | `--Wall` | `--Wextra` |
|------|------|----------|------------|
| `-Wunused-variable` | Unused variable binding | yes | yes |
| `-Wincomplete-patterns` | Non-exhaustive pattern match | yes | yes |
| `-Woverlapping-patterns` | Overlapping case patterns | yes | yes |
| `-Wunhandled-effect` | `perform` without matching `handle` | yes | yes |
| `-Wshadow` | Variable shadowing | no | yes |
| `-Wmissing-signature` | Function without type annotation | no | yes |
| `-Wunused-import` | Imported name not used | no | yes |
---
# Prelude
Source: https://yona-lang.org/reference/prelude/
The Prelude is a Yona module that is automatically loaded for all programs. Its types and functions are available everywhere without an explicit import. This page is the complete reference for the core Prelude surface; utility functions over these types (such as `map` and `unwrapOr` for options) live in the standard library — see [Std\Option](/stdlib/option/) and [Std\Result](/stdlib/result/).
## Types
| Type | Constructors | Purpose |
|------|--------------|---------|
| `Linear a` | `Linear a` | Resource wrapper; must be consumed exactly once |
| `Option a` | `Some a`, `None` | Optional value |
| `Result a e` | `Ok a`, `Err e` | Success or failure |
| `Iterator a` | `Iterator (() -> Option a)` | Pull-based streaming iterator |
All constructors are first-class functions and can be used in pattern matching.
### Linear a
```yona
type Linear a = Linear a
```
Wraps a resource (file handle, socket, process handle) whose lifecycle is tracked by the linearity checker. A `Linear` value must be consumed **exactly once**, by pattern matching. Using it after consumption, consuming it in only one branch of a conditional, or letting it go out of scope unconsumed are compile-time errors (see [error codes](/reference/error-codes/) E0600–E0602).
```yona
let conn = Linear (tcpConnect host port) in
case conn of
Linear fd -> do
send fd "hello"
close fd
end
end
```
### Option a
```yona
type Option a = Some a | None
```
An optional value: `Some x` when a value is present, `None` when it is absent. Functions that may not produce a result return `Option` instead of a sentinel value.
```yona
let safeDiv = (\a b -> if b == 0 then None else Some (a / b)) in
case safeDiv 10 2 of
Some v -> v
None -> 0
end # => 5
```
### Result a e
```yona
type Result a e = Ok a | Err e
```
The outcome of a computation that can fail: `Ok value` on success, `Err error` on failure. The error type `e` is often a symbol or a string.
```yona
let toPort = (\n -> if n > 0 && n < 65536 then Ok n else Err "out of range") in
case toPort 8080 of
Ok p -> p
Err _ -> 0
end # => 8080
```
### Iterator a
```yona
type Iterator a = Iterator (() -> Option a)
```
A pull-based iterator: it wraps a function that returns `Some element` on each call and `None` once exhausted. Streaming producers in the standard library (`readLines`, `chars`, `split`) return `Iterator` so large inputs are processed in O(1) memory. Generators consume iterators as sources, which is the idiomatic way to feed one into a fold:
```yona
import readLines from Std\File, foldl from Std\List in
foldl (\acc _ -> acc + 1) 0 [line for line = readLines "data.txt"]
# => number of lines in the file
```
## Functions
| Function | Signature | Semantics |
|----------|-----------|-----------|
| `identity` | `a -> a` | Returns its argument unchanged |
| `const` | `a -> b -> a` | Ignores its second argument |
| `flip` | `(a -> b -> c) -> b -> a -> c` | Swaps a function's two arguments |
| `compose` | `(b -> c) -> (a -> b) -> a -> c` | Applies `g`, then `f` |
These four combinators are the complete prelude function surface. Collection
folds and transformations (`foldl`, `foldr`, `map`, `filter`, …) are **not**
prelude functions — import them from [Std\List](/stdlib/list/):
```yona
import foldl from Std\List in
foldl (\acc x -> acc + x) 0 [1, 2, 3, 4] # => 10
```
`Std\List.foldl` is tail-recursive, which the compiler turns into a loop —
it never grows the stack. `foldr` recurses to the right and is not
tail-recursive; prefer `foldl` for aggregation over long sequences.
### identity
```yona
identity x = x
```
Returns its argument unchanged. Useful as a default transformation for higher-order functions.
```yona
identity 42 # => 42
identity "yona" # => "yona"
```
### const
```yona
const x _ = x
```
Returns its first argument and ignores the second. Partially applied, `const x` is a function that returns `x` for any input.
```yona
const 1 99 # => 1
let always0 = const 0 in always0 5 # => 0
```
### flip
```yona
flip f a b = f b a
```
Reverses the argument order of a two-argument function.
```yona
flip (\a b -> a - b) 2 10 # => 8
```
### compose
```yona
compose f g x = f (g x)
```
Function composition: applies `g` first, then `f` to the result.
```yona
compose (\x -> x * 2) (\x -> x + 1) 5 # => 12
```
## Other always-available definitions
The Prelude also defines file-I/O and reflection support types — `FileHandle`, `FileMode` (`Read | Write | ReadWrite | Append`), `Whence` (`SeekSet | SeekCur | SeekEnd`), and `Type` (returned by `typeOf`) — as well as the built-in traits `Show`, `Eq`, `Ord`, `Hash`, `Array`, and `Closeable` with instances for the primitive types. See [Std\File](/stdlib/file/) and [Std\Types](/stdlib/types/) for the functions that use them, and the [language specification](/reference/specification/) for trait semantics.
---
# Language specification
Source: https://yona-lang.org/reference/specification/
This document specifies the Yona language as implemented by the reference
compiler `yonac`. Normative rules are stated in prose; *implementation notes*
describe how `yonac` realizes them and are informative, not binding on other
implementations.
A Yona **program is a single expression**. Compiling a source file that
contains an expression produces an executable whose exit code is the
expression's value (for integer results). A source file may instead contain a
**module declaration**, which compiles to a linkable object file plus an
interface file (§7).
## 1. Lexical structure
### 1.1 Source text
Source files are UTF-8. Identifiers are ASCII: functions and variables match
`[a-z_][A-Za-z0-9_]*` (camelCase by convention), type and constructor names
and module segments match `[A-Z][A-Za-z0-9_]*` (PascalCase).
### 1.2 Comments
```yona
# a line comment runs to end of line
## a doc comment — extracted by the API documentation generator
/* a block comment
/* block comments nest */
and may span lines */
```
`#` introduces a line comment. `##` at the start of a line is a documentation
comment, attached to the following declaration by documentation tooling; to
the compiler it is an ordinary comment. `/* … */` comments nest and may
contain newlines.
### 1.3 Newlines
Newlines are significant tokens. A newline (or a `;`, which is equivalent)
terminates an expression in the three positions where expression sequences
occur: **case arms**, **`do`-block steps**, and **module-level function
bodies**.
A newline is *suppressed* — treated as ordinary whitespace — in exactly these
situations:
1. **Inside brackets** `()`, `[]`, `{}`. Bracketed expressions may span any
number of lines. Exception: when a `case`, `do`, `with`, or `handle` block
is open *inside* the brackets, newlines again act as clause separators, so
the block's arms still terminate correctly.
2. **After a binary operator or continuation token** (`+`, `*`, `->`, `=`,
`,`, `|>`, …). This permits natural line continuation:
```yona
let total = price +
tax
in total
```
This rule is what allows juxtaposition application (§3.6) to coexist with
expression sequences: `f x y` never runs onto the next line accidentally,
because the newline ends it unless an operator invites continuation.
### 1.4 Keywords
```
let in do end case of if then else with as
module import export from type trait instance
try catch raise extern async daemon
perform handle resume effect for
```
### 1.5 Literals
| Form | Examples | Notes |
|------|----------|-------|
| Integer | `42`, `-17`, `1_000_000` | 64-bit signed; `_` separators permitted between digits |
| Float | `3.14`, `-0.5`, `1.23e-4` | IEEE 754 double |
| String | `"hello"`, `"a\nb"` | UTF-8; escapes `\"` `\\` `\n` `\r` `\t` `\0`; interpolation §3.2 |
| Character | `'a'`, `'\n'` | single Unicode scalar |
| Boolean | `true`, `false` | |
| Unit | `()` | the empty tuple; the type and value of "nothing" |
| Symbol | `:ok`, `:not_found` | interned atoms, snake_case by convention |
*Implementation note.* Symbols are interned to 64-bit integer identifiers at
compile time; symbol comparison is a single integer comparison, and matching
on symbols compiles to an integer switch.
## 2. Values and their syntax
### 2.1 Collections
```yona
[1, 2, 3] # sequence (persistent list)
[] # empty sequence
(1, "two", true) # tuple — fixed arity, heterogeneous
(42,) # one-element tuple
{1, 2, 3} # set
{"name": "Ada", "age": 36} # dictionary
{} # empty dictionary
```
Sequences, sets, and dictionaries are **persistent**: every operation returns
a new value sharing structure with the old one. Tuples are fixed-arity
product values.
*Implementation note.* Small sequences are flat arrays; large ones are
radix-balanced tries. Dictionaries and sets are hash array mapped tries
(HAMTs). All share structure on update. See
[Persistent data structures](/guides/persistent-data-structures/).
### 2.2 Generators (comprehensions)
```yona
[x * 2 for x = xs] # sequence generator
[x for x = xs, if x > 3] # with guard
{x * 2 for x = xs} # set generator
{k : v * 10 for k = ks} # dictionary generator
[| f x for x = xs ] # parallel generator (§6.3)
```
The general form is `[expr for pattern = source]` with an optional
`, if guard`. The `source` is any sequence-valued expression.
*Implementation note.* Generators compile to counted loops, not closures.
With a guard, a two-pass strategy first counts matches, then fills the
result without reallocation. Chained collection pipelines are stream-fused
into a single loop when the compiler can prove it safe.
## 3. Expressions
### 3.1 `let`
```yona
let x = 42 in x + 1 # single binding
let x = 10, y = 20 in x + y # multiple bindings
let add x y = x + y in add 3 4 # function-definition binding
let (a, b) = (1, 2) in a + b # pattern binding
let _ = println "side effect" in 42 # discard binding
```
`let bindings in body` introduces bindings scoped to `body`. Bindings are
separated by commas. A binding's left side is a pattern; a name followed by
parameter patterns is sugar for binding a lambda. A type annotation may
precede a function binding on its own line:
```yona
let add : Int -> Int -> Int
add x y = x + y
in add 3 4
```
**Evaluation order.** Bindings that depend on earlier bindings observe their
values. Bindings that are *independent* of one another have **no defined
sequential order** and may be evaluated concurrently (§6.2). Code whose side
effects require an order must use `do`.
### 3.2 Strings and interpolation
Within a string literal, `{name}` interpolates a variable and `{(expr)}`
interpolates a parenthesized expression; non-string values are converted to
their textual form:
```yona
let x = 6 in "the answer is {(x * 7)}" # "the answer is 42"
```
### 3.3 `do`
```yona
do
fd = tcpConnect "localhost" 8080 # binding step
send fd "hello" # expression step
response = recv fd 4096
response # value of the block
end
```
`do … end` evaluates its steps **strictly in textual order**. A step of the
form `name = expr` binds `name` for subsequent steps. The block's value is
its last expression. `do` is the sequencing primitive; use it whenever side
effects must happen in order.
### 3.4 `if`
```yona
if x > 0 then "positive"
else if x < 0 then "negative"
else "zero"
```
`if` is an expression; both branches are required and must have the same
type.
### 3.5 Functions and lambdas
```yona
add x y = x + y # space-separated parameter patterns
factorial n = case n of
0 -> 1
_ -> n * factorial (n - 1)
end
abs x if x >= 0 = x # guard; next clause if false
abs x if x < 0 = -x
scale : Float -> Float -> Float # optional annotation
scale factor x = factor * x
\x -> x * 2 # lambda
\(x, y) -> x + y # lambda with tuple pattern
\-> expensive () # zero-argument lambda (thunk)
```
There is no `name(x, y) -> body` definition form. `name (x, y) = body` is a
single tuple pattern, not two parameters.
A function of several clauses is matched top to bottom; the first clause
whose patterns (and guard, if present) match is selected. Functions are
first-class values; partial application is automatic:
```yona
let add5 = add 5 in add5 10 # => 15
```
**Zero-arity functions auto-evaluate** when referenced by name (Yona is
strict). To pass one as a value, wrap it in a thunk: `\-> f`.
### 3.6 Application
Application is by **juxtaposition** — `f x y`. `f(x)` is the same as
`f x`. `f(x, y)` applies `f` to the tuple `(x, y)`; it is not a
two-argument call. Juxtaposition binds tighter than every binary operator:
`f x + g y` parses as `(f x) + (g y)`.
Pipes reverse application order for pipeline style:
```yona
value |> stage1 |> stage2 # stage2 (stage1 value)
stage2 <| stage1 <| value # the same, right-to-left
```
*Implementation note.* `yonac` compiles functions by **deferred
monomorphization**: a definition is stored as a typed AST and compiled at
each call site where concrete argument types are known. Closures capture
free variables in a heap environment; a closure value is
`{fn_ptr, ret_tag, arity, captures…}`.
### 3.7 `case`
```yona
case value of
0 -> "zero"
n if n > 0 -> "positive"
_ -> "negative"
end
```
`case scrutinee of clauses end` evaluates the scrutinee once, then tests
clauses top to bottom (§4 defines patterns). The first matching clause's
body is the expression's value. All clause bodies must have the same type.
If no clause matches at runtime, the program aborts with a match error;
the compiler warns when it can prove a constructor uncovered.
### 3.8 `with` (resources)
```yona
with handle = tcpConnect "localhost" 8080 in
send handle "hello"
# handle is closed when the body completes
```
`with name = resource in body` evaluates `resource`, binds it to `name`,
evaluates `body`, and then releases the resource by calling the `Closeable`
trait's `close` method — resolved statically for the resource's type. Using
a value whose type does not implement `Closeable` is a compile-time error.
*Current limitation.* Release is guaranteed when `body` completes normally.
If an exception propagates out of `body`, `close` is **not** currently
invoked on the unwind path.
### 3.9 Exceptions
```yona
type Error = NotFound String | IOError String
raise (NotFound "config.toml")
try
riskyOperation ()
catch
NotFound path -> "missing: " ++ path
IOError msg -> "io: " ++ msg
_ -> "unknown failure"
end
```
Exception values are ordinary ADT values. `raise` throws; `try … catch …
end` matches the raised value against clauses like a `case`. An unmatched
exception propagates; an uncaught exception terminates the program with a
stack trace.
### 3.10 Algebraic effects Partial
```yona
handle
perform State.get ()
with
State.get () resume -> resume 42
return val -> val
end
```
`perform Effect.op arg` requests the operation `Effect.op` from the nearest
enclosing `handle` that covers it. A handler clause receives the operation's
argument and a `resume` continuation; `return val -> …` transforms the
handled expression's normal result.
Function types carry a **latent effect row** listing the operations the
function may perform: `Int -> !{State.get} Int`. `handle` subtracts the
operations it covers; applying a function whose row is not fully covered at
the top level is error **E0202**, reported at the introducing `perform` with
a note at the call site. Higher-order functions carry open rows (`!{|r}`)
that unify with their argument's row.
*Current limitations.* Handlers are shallow, in-scope dispatch: `resume` is
an identity continuation, not a captured delimited continuation. `effect`
declarations do not parse yet; operations are identified by their
`Effect.op` label at `perform` sites. See
[Effects](/learn/effects/) for the practical guide.
### 3.11 `extern` (C FFI)
```yona
extern sqrt : Float -> Float in
extern pow : Float -> Float -> Float in
sqrt (pow 2.0 10.0) # => 32.0
extern async readFile : String -> String in
readFile "data.txt" # non-blocking; auto-awaited at use
```
`extern name : Type in body` declares an external C symbol with a Yona type;
the linker resolves it. Type mapping: `Int` ↔ `i64`, `Float` ↔ `double`,
`Bool` ↔ `i1`, `String` ↔ `char*`. Curried annotation `A -> B -> C` denotes
a two-argument C function returning `C`. The `async` modifier submits the
call to the runtime's thread pool and yields a promise, awaited
transparently at use sites (§6.2).
## 4. Patterns
| Pattern | Example | Matches |
|---------|---------|---------|
| Literal | `42`, `"hi"`, `:ok`, `true` | that exact value |
| Variable | `x` | anything; binds `x` |
| Wildcard | `_` | anything; binds nothing |
| Tuple | `(a, _, c)` | tuples of that arity |
| Sequence | `[]`, `[x]`, `[a, b]` | sequences of that exact length |
| Head–tail | `[h \| t]`, `[a, b \| rest]` | non-empty sequences; `t`/`rest` bind the remainder |
| Constructor | `Some x`, `Rect w h` | values built by that constructor |
| Record | `Person{name: n}` | matches named fields; others ignored |
| Dictionary | `{"key": v}` | dictionaries containing the key |
| As-binding | `[h \| t] as whole` | matches the inner pattern and binds the whole value |
| Or-pattern | `:a \| :b -> …` | either alternative; both must bind the same names |
| Guard | `n if n > 0 -> …` | pattern matches *and* guard is true |
Patterns appear in `case` clauses, function parameters, `let` bindings, and
`catch` clauses. Matching is left-to-right, top-to-bottom, with no
backtracking within a clause.
## 5. Operators
Precedence, highest to lowest; all binary operators are left-associative
except `**`, `::`, and the arrows:
| Level | Operators | Meaning |
|-------|-----------|---------|
| 1 | `.` | field access |
| 2 | juxtaposition | function application |
| 3 | `**` | power |
| 4 | `!` `~` unary `-` | logical not, bitwise not, negation |
| 5 | `*` `/` `%` | multiplicative |
| 6 | `+` `-` | additive |
| 7 | `<<` `>>` `>>>` | shifts |
| 8 | `++` | concatenation (sequences, strings) |
| 9 | `::` | cons (prepend) |
| 10 | `<` `>` `<=` `>=` | comparison |
| 11 | `==` `!=` | equality |
| 12 | `&` | bitwise and |
| 13 | `^` | bitwise xor |
| 14 | `\|` | bitwise or |
| 15 | `&&` | logical and (short-circuit) |
| 16 | `\|\|` | logical or (short-circuit) |
| 17 | `\|>` `<\|` | pipes |
Sequence-specific operators: `x :: xs` prepends and `xs ++ ys`
concatenates. The lexer reserves `:>` (append), `--` (remove), and `in`
(membership) as operator tokens, but the current compiler does not accept
them in expressions — use `xs ++ [x]`, `Std\List.filter`, and
`Std\List.contains` (or `Std\Set.contains`) instead.
## 6. Evaluation model
### 6.1 Strictness
Yona is strictly evaluated: arguments are evaluated before application, and
bindings before their bodies — with the single systematic exception of
asynchronous values (§6.2). There is no lazy evaluation; laziness is
expressed explicitly with thunks (`\-> e`) or `Iterator`/`Std\Stream`
pipelines.
### 6.2 Transparent asynchrony
Functions that perform I/O (and `extern async` functions) return a
**promise** internally. The type system tracks promises invisibly: when a
promise appears where its underlying value is required — as an operator
operand, function argument, or condition — the compiler inserts an await
coercion. Users never write `async` or `await`, and no function is "colored".
Because `let` bindings without mutual dependencies have no defined order,
independent asynchronous bindings are **submitted before any is awaited**:
```yona
let
a = readFile "foo.txt", # submitted
b = readFile "bar.txt" # submitted
in a ++ b # both awaited here; elapsed ≈ max, not sum
```
*Implementation note.* On Linux, file and network I/O submit to io_uring;
CPU-bound async work runs on a work-stealing thread pool. Buffers passed to
in-flight kernel operations are pinned. See
[Concurrency in depth](/guides/concurrency/).
### 6.3 Parallel generators
`[| f x for x = xs ]` evaluates `f` over the elements concurrently on the
thread pool and preserves order in the result.
### 6.4 Memory
Values are managed by **atomic reference counting** with recursive
destructors; there is no tracing garbage collector and no stop-the-world
pause. The compiler applies Perceus-style ownership transfer (callee-owns
calling convention), uniqueness-based in-place mutation for uniquely owned
values, and escape analysis that arena-allocates values proven not to
escape. See [Memory and linearity](/guides/memory/).
## 7. Types
### 7.1 Inference
The type system is Hindley–Milner: every expression has a principal type,
inferred without annotations. Optional annotations (`name : Type` preceding
a definition) are checked, not trusted. Polymorphic functions are compiled
by monomorphization — one native instantiation per concrete type used.
### 7.2 Algebraic data types
```yona
type Option a = Some a | None
type Result a e = Ok a | Err e
type Tree a = Leaf | Node (Tree a) a (Tree a)
type Lazy a = Cons a (() -> Lazy a) | Empty # function-typed field
type Person = Person { name : String, age : Int } # named fields
```
Constructors are first-class functions. Named-field types support dot
access, record patterns, and functional update:
```yona
let p = Person { name = "Ada", age = 36 } in
(p.name, p { age = 37 })
```
*Implementation note.* Non-recursive ADTs compile to flat
`{tag, payload}` structs; recursive ADTs and ADTs with function-typed
fields are heap-allocated.
### 7.3 Traits Stable
```yona
trait Eq a
eq : a -> a -> Bool
neq : a -> a -> Bool
neq x y = if eq x y then false else true # default method
end
instance Show a => Show (Option a)
show opt = case opt of
Some x -> "Some(" ++ show x ++ ")"
None -> "None"
end
end
trait Eq a => Ord a # superclass constraint
compare : a -> a -> Int
end
```
Traits are type classes resolved **statically**: each call site compiles the
concrete instance directly (monomorphization), with no runtime dispatch
cost. Instances are always public; `export trait Name` exports a
declaration. See [Traits](/guides/traits/).
### 7.4 Effect rows Partial
Function arrows carry the set of effect operations the function may perform:
`a -> !{State.get} Int`. Rows are inferred, unioned at application,
subtracted by `handle`, propagated through `.yonai` interfaces, and kept
open (`!{|r}`) on higher-order parameters. §3.10 lists current limitations.
### 7.5 Linear types Partial
`Linear a` marks values that must be consumed **exactly once**: file
handles, sockets, process handles, channel endpoints. The linearity checker
rejects duplication and silent dropping; `with` is the idiomatic consumer.
`@borrow` marks parameters that use a linear value without consuming it.
See [Memory and linearity](/guides/memory/).
### 7.6 Row-polymorphic records Stable
Record types unify by row: a function using `r.name` accepts any record
containing a `name` field of the right type, and the residual row is
polymorphic.
## 8. Modules
```yona
module Data\Geometry
export area, perimeter
export type Shape
type Shape = Circle Float | Rect Float Float
area s = case s of
Circle r -> 3.141592653589793 * r * r
Rect w h -> w * h
end
perimeter s = case s of
Circle r -> 2.0 * 3.141592653589793 * r
Rect w h -> 2.0 * (w + h)
end
```
A module is a **top-level declaration** — not an expression — and extends to
end of file. `export` statements name exported functions; `export type T`
exports a type with all its constructors; `export f from Other\Module`
re-exports. Module names are backslash-separated paths (`Std\List`).
Imports are expressions:
```yona
import map, filter from Std\List in … # selective
import length as len from Std\String in … # aliased
import Std\Math in … # whole module
Std\List::map (\x -> x + 1) [1, 2, 3] # fully qualified, no import
```
*Implementation note.* A module compiles to a native object file with
C-ABI exports (mangled `yona_Pkg_Mod__func`) and a `.yonai` **interface
file** carrying types, effect rows, linearity, and — for generic functions —
the source text itself (`GENFN`), so a caller with new concrete types can
re-monomorphize the function locally. `yonac -I path` adds interface search
paths. See [Modules and interfaces](/guides/modules-interfaces/).
## 9. Conformance and diagnostics
Compiler diagnostics carry stable codes (`E0100`-style, `W…` for warnings).
`yonac --explain E0202` prints the full explanation for a code. The
[error code index](/reference/error-codes/) lists user-facing codes and
their meanings.
---
# Standard library
Source: https://yona-lang.org/stdlib/
372 public functions across 36 modules.
| Module | Functions | Types | Description |
|--------|-----------|-------|-------------|
| [Std.Bool](/stdlib/bool/) | 7 | 0 | Boolean combinators and conditional helpers. |
| [Std.ByteArray](/stdlib/bytearray/) | 15 | 0 | Contiguous unboxed byte array. |
| [Std.Channel](/stdlib/channel/) | 8 | 2 | Std\Channel — bounded MPMC channels with type-safe sender/receiver split. |
| [Std.Collection](/stdlib/collection/) | 9 | 0 | Higher-order collection operations — functional helpers for sequences, sets, dicts. |
| [Std.Crypto](/stdlib/crypto/) | 4 | 0 | Crypto -- cryptographic hashing and random byte generation. |
| [Std.Dict](/stdlib/dict/) | 9 | 0 | Dict — persistent dictionary backed by a Hash Array Mapped Trie (HAMT). |
| [Std.Encoding](/stdlib/encoding/) | 7 | 0 | Encoding -- string encoding and decoding utilities. |
| [Std.File](/stdlib/file/) | 19 | 0 | File -- filesystem operations with async I/O support. |
| [Std.FloatArray](/stdlib/floatarray/) | 11 | 0 | Contiguous unboxed array of `Float` (64-bit double) values. |
| [Std.Format](/stdlib/format/) | 1 | 0 | Format -- string formatting with positional placeholders. |
| [Std.Function](/stdlib/function/) | 8 | 0 | Function combinators — identity, composition, application, flipping. |
| [Std.GPU](/stdlib/gpu/) | 20 | 1 | Std\GPU — accelerated columnar execution. |
| [Std.Http](/stdlib/http/) | 11 | 3 | HTTP client and server — built on Std\Net and Std\String. |
| [Std.IntArray](/stdlib/intarray/) | 15 | 0 | Contiguous unboxed array of `Int` values. |
| [Std.IO](/stdlib/io/) | 15 | 0 | Std\IO — non-blocking console and handle-based byte I/O. |
| [Std.Json](/stdlib/json/) | 7 | 0 | Json -- JSON serialization helpers. |
| [Std.List](/stdlib/list/) | 29 | 0 | Sequence (list) operations — map, filter, fold, sort, and more. |
| [Std.Log](/stdlib/log/) | 6 | 0 | Log -- leveled logging to stderr. |
| [Std.Math](/stdlib/math/) | 21 | 1 | Math — polymorphic numeric operations and float math. |
| [Std.Net](/stdlib/net/) | 12 | 0 | Net -- TCP and UDP networking with async I/O. |
| [Std.Option](/stdlib/option/) | 10 | 1 | Optional values — represents a value that may or may not exist. |
| [Std.Pair](/stdlib/pair/) | 9 | 1 | ADT-based pairs with named fields — an alternative to tuples. |
| [Std.Parallel](/stdlib/parallel/) | 2 | 0 | |
| [Std.Path](/stdlib/path/) | 6 | 0 | Path -- file path manipulation. |
| [Std.Process](/stdlib/process/) | 15 | 0 | Process -- process management, environment, and command execution. |
| [Std.Random](/stdlib/random/) | 4 | 0 | Random -- pseudo-random number generation. |
| [Std.Range](/stdlib/range/) | 11 | 0 | Integer ranges with optional step — lazy representation, materialized on demand. |
| [Std.Regex](/stdlib/regex/) | 7 | 0 | Regex — PCRE2-backed regular expressions. |
| [Std.Result](/stdlib/result/) | 11 | 1 | Error handling — represents either success (`Ok value`) or failure (`Err error`). |
| [Std.Set](/stdlib/set/) | 9 | 0 | Set — persistent set backed by a Hash Array Mapped Trie (HAMT). |
| [Std.String](/stdlib/string/) | 27 | 0 | String -- string manipulation and conversion. |
| [Std.Task](/stdlib/task/) | 1 | 0 | Task spawning for concurrent execution. |
| [Std.Test](/stdlib/test/) | 6 | 0 | Simple test assertions — returns `(:pass, name)` or `(:fail, message)`. |
| [Std.Time](/stdlib/time/) | 6 | 0 | Time -- timestamps, sleeping, and elapsed time measurement. |
| [Std.Tuple](/stdlib/tuple/) | 9 | 0 | Operations on 2-tuples (pairs). |
| [Std.Types](/stdlib/types/) | 5 | 0 | Types -- runtime type conversions. |
---
# Std\Bool
Source: https://yona-lang.org/stdlib/bool/
Boolean combinators and conditional helpers.
Provides logical operations beyond the built-in `&&` and `||` operators,
plus conditional execution helpers.
## Functions
### `not : Int -> Bool`
Logical negation.
```yona
not true # => false
not false # => true
```
### `and : Int -> Int -> Int`
Logical AND (short-circuiting).
```yona
and true true # => true
and true false # => false
```
### `or : Int -> Int -> Bool`
Logical OR (short-circuiting).
```yona
or false true # => true
or false false # => false
```
### `xor : Int -> Int -> Bool`
Exclusive OR — true when exactly one argument is true.
```yona
xor true false # => true
xor true true # => false
```
### `implies : Int -> Int -> Int`
Logical implication: `a → b`. False only when `a` is true and `b` is false.
```yona
implies true true # => true
implies true false # => false
implies false true # => true
```
### `when : Int -> (a -> b) -> Int`
Executes `fn ()` if `cond` is true, otherwise returns `:ok`.
```yona
when true (\-> 42) # => 42
when false (\-> 42) # => :ok
```
### `unless : Int -> (a -> b) -> Symbol`
Executes `fn ()` if `cond` is false, otherwise returns `:ok`.
```yona
unless false (\-> 42) # => 42
unless true (\-> 42) # => :ok
```
---
# Std\ByteArray
Source: https://yona-lang.org/stdlib/bytearray/
Contiguous unboxed byte array. Provides allocation, indexing, slicing,
bulk operations (foldl, map), and conversion between byte arrays,
strings, and sequences. Used for binary I/O, network protocols,
and interop with C libraries. Implements the `Array` trait.
## Functions
### `alloc : Int -> ByteArray`
Allocate a zero-filled byte buffer of `size` bytes.
```yona
import alloc from Std\ByteArray in
let buf = alloc 1024 in
length buf # => 1024
```
### `length : ByteArray -> Int`
Returns the number of bytes in the buffer.
```yona
import length from Std\ByteArray in
length (fromString "hello") # => 5
```
### `get : ByteArray -> Int -> Int`
Returns the byte value (0-255) at the given index.
```yona
import get, fromString from Std\ByteArray in
let buf = fromString "ABC" in
get buf 0 # => 65
```
### `set : ByteArray -> Int -> Int -> ()`
Sets the byte at `index` to `value` (0-255). Mutates the buffer in place.
```yona
import alloc, set, get from Std\ByteArray in
let buf = alloc 4 in
do
set buf 0 42
get buf 0 # => 42
end
```
### `concat : ByteArray -> ByteArray -> ByteArray`
Concatenate two byte buffers into a new buffer.
```yona
import concat, fromString from Std\ByteArray in
let buf = concat (fromString "hello ") (fromString "world") in
toString buf # => "hello world"
```
### `slice : ByteArray -> Int -> Int -> ByteArray`
Extract a sub-buffer from index `start` (inclusive) to `end` (exclusive).
```yona
import slice, fromString, toString from Std\ByteArray in
toString (slice (fromString "hello") 1 4) # => "ell"
```
### `fromString : String -> ByteArray`
Convert a UTF-8 string to a byte buffer.
```yona
import fromString from Std\ByteArray in
let buf = fromString "hi" in
length buf # => 2
```
### `toString : ByteArray -> String`
Convert a byte buffer back to a UTF-8 string.
```yona
import fromString, toString from Std\ByteArray in
toString (fromString "hello") # => "hello"
```
### `fromSeq : [a] -> ByteArray`
Create a byte buffer from a sequence of integers (0-255).
```yona
import fromSeq, get from Std\ByteArray in
let buf = fromSeq [72, 105] in
get buf 0 # => 72
```
### `toSeq : ByteArray -> [a]`
Convert a byte buffer to a sequence of integers.
```yona
import fromString, toSeq from Std\ByteArray in
toSeq (fromString "Hi") # => [72, 105]
```
### `head : ByteArray -> Int`
First byte value. O(1).
### `tail : ByteArray -> ByteArray`
All bytes except the first. Returns a new array.
### `join : ByteArray -> ByteArray -> ByteArray`
Concatenate two byte arrays (alias for `concat`).
### `foldl : (a -> b) -> Int -> ByteArray -> Int`
Left fold over all bytes. Single-pass, cache-friendly.
```yona
import fromString, foldl from Std\ByteArray in
foldl (\acc b -> acc + b) 0 (fromString "ABC") -- 65+66+67 = 198
```
### `map : (a -> b) -> ByteArray -> ByteArray`
Apply a function to each byte, returning a new array.
---
# Std\Channel
Source: https://yona-lang.org/stdlib/channel/
Std\Channel — bounded MPMC channels with type-safe sender/receiver split.
`channel n` returns `(Linear (Sender a), Linear (Receiver a))`. The
linearity checker enforces that each side is unwrapped from `Linear`
exactly once via pattern match. After unwrapping, a `Sender a` can only
`send` and a `Receiver a` can only `recv` / `tryRecv`, enforcing the
producer/consumer split at the type level.
See `docs/api/Channel.md` for the full API.
## Types
### Sender
`type Sender a = Sender Channel`
Send-only handle wrapping a Channel.
### Receiver
`type Receiver a = Receiver Channel`
Receive-only handle wrapping a Channel.
## Functions
### `channel : Int -> (Linear (Sender a), Linear (Receiver a))`
Create a bounded channel with the given buffer capacity. Returns a tuple
of `Linear`-wrapped sender and receiver handles. The linearity checker
requires both wrappers to be unwrapped before scope exit:
```yona
let (sl, rl) = channel 16 in
case sl of Linear sender ->
case rl of Linear receiver ->
... -- use sender / receiver freely
end end
```
### `send : Sender a -> a -> ()`
Send a value through a sender. Blocks if the buffer is full.
### `recv : Receiver a -> Option a`
Receive a value. Blocks if the buffer is empty. Returns `Some v` for a
delivered value or `None` once the channel is closed and drained.
### `tryRecv : Receiver a -> Option a`
Non-blocking receive — returns immediately even if empty.
### `close : Sender a -> ()`
Close the sender side. Wakes all blocked sends and recvs.
### `isClosed : Sender a -> Bool`
Returns true if the channel has been closed.
### `length : Sender a -> Int`
Current number of buffered elements.
### `capacity : Sender a -> Int`
Maximum buffer size (set at creation).
---
# Std\Collection
Source: https://yona-lang.org/stdlib/collection/
Higher-order collection operations — functional helpers for sequences, sets, dicts.
Provides iterate, unfold, repeat, cycle, and windowing operations
that complement the core List module.
## Functions
### `iterate : Int -> (a -> b) -> Int -> [b]`
Generates a sequence by repeatedly applying `fn` to a seed value.
Returns the first `n` values: `[seed, fn(seed), fn(fn(seed)), ...]`.
```yona
iterate 5 (\x -> x * 2) 1 # => [1, 2, 4, 8, 16]
```
### `unfold : (a -> b) -> Int -> [b]`
Generates a sequence from a seed using a producer function.
`fn seed` returns `(:some, (value, next_seed))` to continue, `:none` to stop.
```yona
unfold (\n -> if n > 0 then (:some, (n, n - 1)) else :none) 5
# => [5, 4, 3, 2, 1]
```
### `replicate : Int -> Int -> [a]`
Creates a sequence of `n` copies of `value`.
```yona
replicate 3 42 # => [42, 42, 42]
```
### `tabulate : Int -> (a -> b) -> [b]`
Creates a sequence by applying `fn` to indices `0..n-1`.
```yona
tabulate 4 (\i -> i * i) # => [0, 1, 4, 9]
```
### `window : Int -> [a] -> [b]`
Sliding window of size `size` over a sequence.
Returns a sequence of sub-sequences (represented as sequences).
```yona
window 2 [1, 2, 3, 4] # => [[1, 2], [2, 3], [3, 4]]
```
### `chunks : Int -> [a] -> [b]`
Splits a sequence into chunks of size `size`.
```yona
chunks 2 [1, 2, 3, 4, 5] # => [[1, 2], [3, 4], [5]]
```
### `pairwise : [a] -> [b]`
Returns consecutive pairs from a sequence.
```yona
pairwise [1, 2, 3, 4] # => [(1, 2), (2, 3), (3, 4)]
```
### `dedup : [a] -> [b]`
Removes consecutive duplicates.
```yona
dedup [1, 1, 2, 2, 3, 1, 1] # => [1, 2, 3, 1]
```
### `frequencies : [a] -> [b]`
Counts occurrences of each element. Returns sequence of `(element, count)` pairs.
```yona
frequencies [1, 2, 1, 3, 2, 1] # => [(1, 3), (2, 2), (3, 1)]
```
---
# Std\Crypto
Source: https://yona-lang.org/stdlib/crypto/
Crypto -- cryptographic hashing and random byte generation.
Provides SHA-256 hashing, cryptographically secure random bytes,
and UUID v4 generation.
## Functions
### `sha256 : String -> String`
Compute the SHA-256 hash of a string. Returns the hex-encoded digest.
```yona
import sha256 from Std\Crypto in
sha256 "hello" # => "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
```
### `randomBytes : Int -> String`
Generate `n` cryptographically secure random bytes, returned as a raw string.
```yona
import randomBytes from Std\Crypto in
let key = randomBytes 32 in
length key # => 32
```
### `randomHex : Int -> String`
Generate `n` random bytes and return them as a hex-encoded string (2n characters).
```yona
import randomHex from Std\Crypto in
randomHex 16 # => "a3f2b1..." (32 hex characters)
```
### `uuid4 : String`
Generate a random UUID v4 string.
```yona
import uuid4 from Std\Crypto in
uuid4 # => "550e8400-e29b-41d4-a716-446655440000"
```
---
# Std\Dict
Source: https://yona-lang.org/stdlib/dict/
Dict — persistent dictionary backed by a Hash Array Mapped Trie (HAMT).
Provides immutable key-value mappings with O(log32 n) lookup, insert,
and update. Iterators use stack-based trie traversal with O(1) memory
per element.
## Functions
### `put : Dict a b -> a -> b -> Dict a b`
Insert or update a key-value pair. Returns a new dictionary with the
mapping added. The original dictionary is unchanged.
```yona
let d = put {} 1 100 in
let d2 = put d 2 200 in
get d2 1 0 # => 100
```
### `get : Dict a b -> a -> b -> b`
Look up the value for `key`. Returns `default` if the key is not present.
```yona
let d = put {} 42 999 in
get d 42 0 # => 999
get d 99 0 # => 0
```
### `contains : Dict a b -> a -> Bool`
Check whether `key` exists in the dictionary. Returns `true` or `false`.
```yona
let d = put {} 1 10 in
contains d 1 # => true
contains d 2 # => false
```
### `size : Dict a b -> Int`
Returns the number of entries in the dictionary.
```yona
let d = put (put {} 1 10) 2 20 in
size d # => 2
```
### `keys : Dict a b -> [a]`
Eagerly collects all keys into a sequence.
```yona
let d = put (put {} 1 10) 2 20 in
keys d # => [1, 2] (order may vary)
```
### `entries : Dict a b -> Iterator (a, b)`
Returns a streaming `Iterator (Int, Int)` over `(key, value)` tuples.
Uses stack-based trie traversal — O(1) memory per element.
```yona
let d = put (put {} 1 10) 2 20 in
forEach (\k v -> println (show k ++ " => " ++ show v)) d
```
### `keysIter : Dict a b -> Iterator a`
Returns a streaming `Iterator Int` over keys. O(1) memory per element.
```yona
import keysIter from Std\Dict in
let d = put (put {} 1 10) 2 20 in
let iter = keysIter d in
# consume with iterator protocol
```
### `values : Dict a b -> Iterator b`
Returns a streaming `Iterator Int` over values. O(1) memory per element.
```yona
import values from Std\Dict in
let d = put (put {} 1 10) 2 20 in
let iter = values d in
# consume with iterator protocol
```
### `forEach : (a -> b -> c) -> Dict a b -> ()`
Apply `callback` to each `(key, value)` entry for side effects.
The callback receives two arguments: the key and the value.
```yona
let d = put (put {} 1 10) 2 20 in
forEach (\k v -> println (show k ++ ": " ++ show v)) d
```
---
# Std\Encoding
Source: https://yona-lang.org/stdlib/encoding/
Encoding -- string encoding and decoding utilities.
Provides Base64, hex, URL percent-encoding, and HTML entity escaping.
## Functions
### `base64Encode : String -> String`
Encode a string to Base64.
```yona
import base64Encode from Std\Encoding in
base64Encode "hello" # => "aGVsbG8="
```
### `base64Decode : String -> String`
Decode a Base64-encoded string back to its original form.
```yona
import base64Decode from Std\Encoding in
base64Decode "aGVsbG8=" # => "hello"
```
### `hexEncode : String -> String`
Encode each byte of a string as two hex characters.
```yona
import hexEncode from Std\Encoding in
hexEncode "AB" # => "4142"
```
### `hexDecode : String -> String`
Decode a hex-encoded string back to bytes.
```yona
import hexDecode from Std\Encoding in
hexDecode "4142" # => "AB"
```
### `urlEncode : String -> String`
Percent-encode a string for use in URLs.
```yona
import urlEncode from Std\Encoding in
urlEncode "hello world" # => "hello%20world"
```
### `urlDecode : String -> String`
Decode a percent-encoded URL string.
```yona
import urlDecode from Std\Encoding in
urlDecode "hello%20world" # => "hello world"
```
### `htmlEscape : String -> String`
Escape HTML special characters (`<`, `>`, `&`, `"`, `'`) to their entity equivalents.
```yona
import htmlEscape from Std\Encoding in
htmlEscape "hi" # => "<b>hi</b>"
```
---
# Std\File
Source: https://yona-lang.org/stdlib/file/
File -- filesystem operations with async I/O support.
Provides file reading, writing, directory listing, and low-level
file handle operations. Async functions (`readFile`, `readFileBytes`,
`readBytes`, `writeBytes`) use io_uring on Linux for non-blocking I/O.
## Functions
### `readFile : String -> String`
Read the entire contents of a file as a string. Async (io_uring).
```yona
import readFile from Std\File in
let contents = readFile "data.txt" in
println contents
```
### `writeFile : String -> String -> Bool`
Write a string to a file, creating or overwriting it. Async (io_uring).
Returns `true` on success.
```yona
import writeFile from Std\File in
writeFile "out.txt" "hello world" # => true
```
### `appendFile : String -> String -> Bool`
Append a string to a file. Returns `true` on success.
```yona
import appendFile from Std\File in
appendFile "log.txt" "new line\n" # => true
```
### `exists : String -> Bool`
Check whether a file or directory exists at the given path.
```yona
import exists from Std\File in
exists "/tmp" # => true
```
### `remove : String -> Bool`
Delete a file. Returns `true` on success.
```yona
import remove from Std\File in
remove "temp.txt" # => true
```
### `size : String -> Int`
Returns the size of a file in bytes.
```yona
import size from Std\File in
size "data.bin" # => 4096
```
### `listDir : String -> [a]`
List directory contents. Returns a sequence of filenames.
```yona
import listDir from Std\File in
listDir "/tmp" # => ["file1.txt", "file2.txt", ...]
```
### `readLines : String -> Iterator a`
Returns an `Iterator String` that yields lines from the file lazily.
Uses O(1) memory per element.
```yona
import readLines from Std\File in
let iter = readLines "big.csv" in
# consume with iterator protocol
```
### `readFileBytes : String -> ByteArray`
Read the entire file as a byte buffer. Async (io_uring).
```yona
import readFileBytes from Std\File in
let buf = readFileBytes "image.png" in
Bytes::length buf
```
### `writeFileBytes : String -> ByteArray -> Bool`
Write a byte buffer to a file. Returns `true` on success.
```yona
import writeFileBytes from Std\File in
import fromSeq from Std\ByteArray in
writeFileBytes "out.bin" (fromSeq [0, 1, 2, 3])
```
### `openFile : String -> FileMode -> FileHandle`
Open a file with the given mode string (`"r"`, `"w"`, `"rw"`, etc.).
Returns a file descriptor (Int).
```yona
import openFile, closeFileHandle from Std\File in
let fd = openFile "data.txt" Read in
closeFileHandle fd
```
The mode is a `FileMode` ADT (Prelude): `Read`, `Write`, `ReadWrite`, `Append`.
### `closeFileHandle : Int -> ()`
Close a file descriptor.
### `readBytes : Int -> Int -> ByteArray`
Read up to `count` bytes from a file descriptor. Async (io_uring).
Returns a byte buffer.
### `writeBytes : Int -> Int -> Int`
Write bytes to a file descriptor. Async (io_uring).
Returns the number of bytes written.
### `seek : Int -> Int -> a -> Int`
Seek to a position in a file. `whence` is a `Whence` ADT (Prelude):
`SeekSet` (absolute), `SeekCur` (relative to current), `SeekEnd` (relative to end).
Returns the new position.
```yona
import openFile, seek, tell from Std\File in
let fd = openFile "data.bin" "r" in
seek fd 100 "set"
```
### `tell : Int -> Int`
Returns the current position in a file descriptor.
### `flush : Int -> Bool`
Flush buffered writes for a file descriptor. Returns `true` on success.
### `truncate : Int -> Int -> Bool`
Truncate a file to the given length. Returns `true` on success.
### `readChunks : Int -> Int -> Iterator a`
Read data from a file descriptor in chunks of `chunkSize` bytes.
Returns a handle for chunked reading.
---
# Std\FloatArray
Source: https://yona-lang.org/stdlib/floatarray/
Contiguous unboxed array of `Float` (64-bit double) values. No per-element
reference counting. O(1) random access, cache-friendly iteration.
## Functions
### alloc
```yona
alloc : Int -> FloatArray
```
Allocate an uninitialized FloatArray with the given number of elements.
### fill
```yona
fill : Int -> Float -> FloatArray
```
Create a FloatArray of `n` elements, all set to the given value.
```yona
import fill from Std\FloatArray in
fill 1000 0.0 -- 1000 zeros
```
### length
```yona
length : FloatArray -> Int
```
O(1) element count.
### get
```yona
get : FloatArray -> Int -> Float
```
O(1) indexed access.
### set
```yona
set : FloatArray -> Int -> Float -> FloatArray
```
Persistent set — returns a new array with the element replaced.
### head
```yona
head : FloatArray -> Float
```
First element. O(1).
### tail
```yona
tail : FloatArray -> FloatArray
```
All elements except the first.
### cons
```yona
cons : Float -> FloatArray -> FloatArray
```
Prepend an element.
### join
```yona
join : FloatArray -> FloatArray -> FloatArray
```
Concatenate two arrays.
### map
```yona
map : (Float -> Float) -> FloatArray -> FloatArray
```
Apply a function to each element. SIMD-eligible for simple operations.
### foldl
```yona
foldl : (Float -> Float -> Float) -> Float -> FloatArray -> Float
```
Left fold over all elements.
```yona
import fill, foldl from Std\FloatArray in
foldl (\acc x -> acc + x) 0.0 (fill 100 1.5) -- 150.0
```
---
# Std\Format
Source: https://yona-lang.org/stdlib/format/
Format -- string formatting with positional placeholders.
Provides printf-style string formatting using `{}` placeholders
filled from a sequence of values.
## Functions
### `format : String -> [a] -> String`
Format a template string by replacing `{}` placeholders with values
from the `args` sequence, in order.
```yona
import format from Std\Format in
format "Hello, {}! You are {} years old." ["Alice", "30"]
# => "Hello, Alice! You are 30 years old."
```
---
# Std\Function
Source: https://yona-lang.org/stdlib/function/
Function combinators — identity, composition, application, flipping.
These are the fundamental higher-order function building blocks.
## Functions
### `identity : Int -> Int`
Returns its argument unchanged.
```yona
identity 42 # => 42
```
### `const : Int -> Int -> Int`
Creates a function that always returns `value`, ignoring its argument.
```yona
let always5 = const 5 in always5 99 # => 5
```
### `compose : (a -> b) -> (c -> d) -> Int -> Int`
Composes two functions: `(compose f g) x = f (g x)`.
```yona
let double = \x -> x * 2 in
let inc = \x -> x + 1 in
compose double inc 3 # => 8 (double(inc(3)) = double(4) = 8)
```
### `flip : (a -> b) -> Int -> Int -> Int`
Swaps the arguments of a two-argument function.
```yona
let sub = \a b -> a - b in
flip sub 3 10 # => 7 (sub 10 3)
```
### `on : (a -> b) -> (c -> d) -> Int -> Int -> Int`
Applies a function to both arguments before combining.
`(on cmp f) a b = cmp (f a) (f b)`
```yona
let compareLength = on (\a b -> a - b) (\s -> length s) in
compareLength [1,2,3] [1,2] # => 1
```
### `apply : Int -> (a -> b) -> Int`
Applies a function to a value (flip of function application).
```yona
apply 42 (\x -> x + 1) # => 43
```
### `pipe : Int -> [a] -> Int`
Pipes a value through a chain of functions (left to right).
`pipe x [f, g, h] = h (g (f x))`
```yona
let fns = [\x -> x + 1, \x -> x * 2, \x -> x - 3] in
pipe 5 fns # => 9 ((5+1)*2-3 = 9)
```
### `fix : (a -> b) -> Int`
Fixed-point combinator for anonymous recursion.
`fix f = f (fix f)` — enables recursion without naming.
```yona
let factorial = fix (\self n -> if n <= 1 then 1 else n * (self (n - 1))) in
factorial 5 # => 120
```
---
# Std\GPU
Source: https://yona-lang.org/stdlib/gpu/
Std\GPU — accelerated columnar execution.
The initial backend is portable CPU execution over `IntArray` columns. It
keeps explicit upload/materialize boundaries so programs are ready for future
Vulkan or vendor-backed device storage without changing the high-level API.
With `YONA_COMPILE_GPU_VULKAN`, optional Vulkan compute can handle `mapAdd`,
`mapMul`, `reduceSum`, and `filterGreaterThan` (see `docs/gpu-architecture.md`).
`mapAdd`/`mapMul`/`reduceSum`/`filterGreaterThan` prefer device-local SSBOs with staging
when VRAM allows; set `YONA_GPU_VULKAN_HOST_SSBO=1` to force the legacy host-mapped SSBO path.
`filterGreaterThan` uses GPU mark + GPU inclusive prefix + exclusive indices +
GPU scatter when enabled (`YONA_GPU_VULKAN_FILTER` or `YONA_GPU_VULKAN_COMPUTE`).
Set `YONA_GPU_VULKAN_FILTER_CPU_PREFIX=1` to force the older host-side prefix (debug only).
## Types
### Buffer
`type Buffer = Buffer IntArray`
Opaque accelerator buffer. The CPU backend stores an owned IntArray copy.
## Functions
### `backendName : String`
Active backend name. Currently `cpu-simd` or `cpu-scalar`.
### `vulkanStatus : String`
Vulkan status string: `vulkan-unavailable`, `vulkan-loader`, or `vulkan-device`
(device only when built with Vulkan headers and init succeeded).
### `vulkanLastNote : String`
Short hint from the last failed Vulkan init, opt-in int column GPU attempt,
async **`vkWaitForFences`**, or other **`VkResult`** failures on the **`Std\GPU`**
float path / test dispatch (`gpu_stub.c`). After a successful device init
without **`shaderInt64`** (typical MoltenVK / Metal), records that IntArray
GPU kernels use i32 when values fit. Empty after int64-capable success or when
Vulkan was not compiled in. Same source as the C **`yona_gpu_vulkan_device_last_note()`**
helper.
### `vulkanLastIssueKind : Int`
0 = no classified **VkResult** yet; 1 = out-of-memory; 2 = device lost; 3 = other
(updated with **`vulkanLastNote`** when the runtime records a **`VkResult`**).
### `hasGpu : Bool`
True when Vulkan is enabled at build, not disabled by `YONA_GPU_DISABLE_VULKAN`,
and device init succeeds. IntArray kernels use i64 when `shaderInt64` is
available, otherwise i32 when values fit. Result is cached until
`yona_gpu_vulkan_device_shutdown()`.
### `hasSimd : Bool`
True when the CPU backend was built with a known SIMD baseline.
### `vulkanAvailable : Bool`
True when a Vulkan loader is visible to the process (`vulkan-1.dll`,
`libvulkan.so.1`, or on macOS `libvulkan.1.dylib` / `libMoltenVK.dylib`
via `VULKAN_SDK`, `HOMEBREW_PREFIX`, or the lib dir CMake recorded).
### `vulkanTimelineSemaphore : Bool`
True when device init succeeded (see **`hasGpu`** / **`vulkanStatus`**) and the
probe finds timeline semaphores: Vulkan 1.2+ **`timelineSemaphore`** via **`vkGetPhysicalDeviceFeatures2`**
(Vulkan 12 feature chain), or **`VK_KHR_timeline_semaphore`** in the device's extension list
(Vulkan 1.0/1.1 stacks that expose the capability only as an extension). When
**`VK_KHR_synchronization2`** is enabled on the lazy **`gpu_stub`** device, async
float compute may wait on a **timeline semaphore** instead of a fence (**`YONA_GPU_ASYNC_TIMELINE=0`**
forces the legacy fence path).
### `available : () -> Bool`
### `apiVersion : () -> Int`
### `physicalDeviceCount : () -> Int`
### `upload : IntArray -> Buffer`
Copy a host IntArray into accelerator-owned storage.
### `materialize : Buffer -> IntArray`
Copy accelerator-owned storage back to a host IntArray.
### `length : Buffer -> Int`
Number of elements in the buffer.
### `mapAdd : Int -> Buffer -> Buffer`
Add a constant to every element. Vulkan path when `YONA_GPU_VULKAN_MAPADD=1`
or `YONA_GPU_VULKAN_COMPUTE=1` and length ≥ min (default 4096; see docs).
### `mapMul : Int -> Buffer -> Buffer`
Multiply every element by a constant. Vulkan when `YONA_GPU_VULKAN_MAPMUL=1`
or `YONA_GPU_VULKAN_COMPUTE=1` (min length env vars in docs).
### `filterGreaterThan : Int -> Buffer -> Buffer`
Keep values greater than the threshold. Vulkan when `YONA_GPU_VULKAN_FILTER`
or `YONA_GPU_VULKAN_COMPUTE=1` and length thresholds are met (`docs/gpu-architecture.md`).
### `reduceSum : Buffer -> Int`
Sum all values. Vulkan when `YONA_GPU_VULKAN_REDUCE=1` or
`YONA_GPU_VULKAN_COMPUTE=1` (min length in docs); else SIMD/scalar CPU.
### `floatArrayMul2Async : FloatArray -> Int`
Experimental: in-place x2 on `FloatArray` via native promise (see `docs/design-gpu-async.md`).
The C wrapper creates the `VkDevice`/pools on first use (`yona_gpu_vulkan_ctx_init`) when built with Vulkan.
### `floatArrayScaleAsync : Float -> FloatArray -> Int`
In-place multiply each element by `scale` (same Vulkan path as `floatArrayMul2Async`).
---
# Std\Http
Source: https://yona-lang.org/stdlib/http/
HTTP client and server — built on Std\Net and Std\String.
Provides Request/Response types, high-level client (get, post),
and a simple server (serve). All networking via io_uring.
## Types
### Method
`type Method = GET | POST | PUT | DELETE | PATCH | HEAD | OPTIONS`
HTTP method.
### Request
```yona
type Request = Request {
method : Method,
path : String,
headers : Int,
body : String
}
```
HTTP request with method, path, headers, and body.
### Response
```yona
type Response = Response {
status : Int,
rawHeaders : String,
body : String
}
```
HTTP response with status code, raw headers string, and body.
## Functions
### `get : String -> Int -> String -> Response`
HTTP GET shorthand.
```yona
get "example.com" 80 "/api"
```
### `post : String -> Int -> String -> String -> Response`
HTTP POST shorthand.
```yona
post "example.com" 80 "/submit" "key=value"
```
### `request : Method -> String -> Int -> String -> Request`
Create a request with defaults.
### `send : String -> Int -> Request -> Response`
Send an HTTP request to host:port and return the Response.
```yona
send "example.com" 80 (request GET "/" 0 "")
```
### `parseResponse : String -> Response`
Parse an HTTP response string into a Response.
### `formatRequest : String -> Request -> String`
Format a Request into an HTTP/1.1 request string.
### `serve : String -> Int -> (Request -> Response) -> Int`
Start an HTTP server. Calls `handler request` for each incoming connection.
The handler receives a Request and returns a Response.
Runs forever (blocking).
```yona
serve "0.0.0.0" 8080 (\req -> ok "Hello!")
```
### `response : Int -> String -> Response`
Create a Response with custom status and body.
### `ok : String -> Response`
Create a simple 200 OK response.
```yona
ok "Hello, World!"
```
### `notFound : Response`
Create a 404 Not Found response.
### `serverError : Response`
Create a 500 Internal Server Error response.
---
# Std\IntArray
Source: https://yona-lang.org/stdlib/intarray/
Contiguous unboxed array of `Int` values. No per-element reference counting —
the array itself is a single RC-managed allocation. O(1) random access,
cache-friendly iteration, SIMD auto-vectorizable by LLVM.
Implements the `Array` trait — `length` and `get` work via trait dispatch
without explicit imports. The Prelude's polymorphic `foldl` also works on
IntArray via runtime type detection.
```yona
import fromSeq from Std\IntArray in
let arr = fromSeq [1, 2, 3, 4, 5] in
length arr -- 5 (Array trait)
get arr 2 -- 3 (Array trait)
foldl (\a b -> a + b) 0 arr -- 15 (polymorphic Prelude foldl)
```
## Functions
### alloc
```yona
alloc : Int -> IntArray
```
Allocate an uninitialized IntArray with the given number of elements.
### fill
```yona
fill : Int -> Int -> IntArray
```
Create an IntArray of `n` elements, all set to the given value.
```yona
import fill from Std\IntArray in
fill 1000 0 -- 1000 zeros
```
### length
```yona
length : IntArray -> Int
```
O(1) element count.
### get
```yona
get : IntArray -> Int -> Int
```
O(1) indexed access. No bounds checking.
```yona
import fromSeq, get from Std\IntArray in
get (fromSeq [10, 20, 30]) 1 -- 20
```
### set
```yona
set : IntArray -> Int -> Int -> IntArray
```
Persistent set — returns a new array with the element at the given index
replaced. O(n) copy.
### head
```yona
head : IntArray -> Int
```
First element. O(1).
### tail
```yona
tail : IntArray -> IntArray
```
All elements except the first. Returns a new array. O(n) copy.
### cons
```yona
cons : Int -> IntArray -> IntArray
```
Prepend an element. Returns a new array. O(n) copy.
### join
```yona
join : IntArray -> IntArray -> IntArray
```
Concatenate two arrays. O(n+m).
### slice
```yona
slice : IntArray -> Int -> Int -> IntArray
```
Extract a sub-array starting at `start` with `length` elements.
```yona
import fromSeq, slice, foldl from Std\IntArray in
foldl (\acc x -> acc + x) 0 (slice (fromSeq [10, 20, 30, 40, 50]) 1 3)
-- 90 (20 + 30 + 40)
```
### map
```yona
map : (Int -> Int) -> IntArray -> IntArray
```
Apply a function to each element, returning a new array. Single-pass,
SIMD-eligible for simple operations.
```yona
import fromSeq, map, foldl from Std\IntArray in
foldl (\acc x -> acc + x) 0 (map (\x -> x * x) (fromSeq [1, 2, 3, 4, 5]))
-- 55
```
### foldl
```yona
foldl : (Int -> Int -> Int) -> Int -> IntArray -> Int
```
Left fold over all elements. Single-pass, cache-friendly.
```yona
import fill, foldl from Std\IntArray in
foldl (\acc x -> acc + x) 0 (fill 100 1) -- 100
```
### filter
```yona
filter : (Int -> Bool) -> IntArray -> IntArray
```
Keep elements satisfying the predicate. Two-pass (count + fill).
```yona
import fromSeq, filter, foldl from Std\IntArray in
foldl (\acc x -> acc + x) 0 (filter (\x -> x % 2 == 0) (fromSeq [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
-- 30
```
### fromSeq
```yona
fromSeq : [Int] -> IntArray
```
Convert a sequence to an IntArray. O(n) copy from boxed to unboxed.
### toSeq
```yona
toSeq : IntArray -> [Int]
```
Convert an IntArray to a sequence. O(n) copy from unboxed to boxed.
---
# Std\IO
Source: https://yona-lang.org/stdlib/io/
Std\IO — non-blocking console and handle-based byte I/O.
Every operation that can block on a slow device submits through
io_uring (on Linux) or the thread pool (for reads), returns a
`Promise`, and auto-awaits at the use site. The only synchronous
calls are pure syscalls that never block — `isTty`, `flush`.
Trivial programs stay trivial: `println "hello"` is still one line.
The non-blocking machinery is invisible until you put several I/O
calls in a let block, at which point the structured-concurrency
grouping runs them concurrently.
```yona
import println, readLine from Std\IO in
do
println "What is your name?"
case readLine of
Some name -> println "Hello, {name}"
None -> println "Goodbye."
end
end
```
## Functions
### `stdinFd : Int = 0`
File descriptor numbers, exposed as Int so any Std\File handle call
that expects `FileHandle` can be wrapped — `FileHandle stdoutFd`
builds the Linear-compatible handle — and the raw int is also useful
for passing to `write` without constructing the ADT.
### `stdoutFd : Int = 1`
### `stderrFd : Int = 2`
### `print : String -> ()`
Write `s` to stdout. Returns a Promise that resolves when the kernel
has accepted the write. Non-blocking.
### `println : String -> ()`
Write `s` followed by a newline to stdout. Non-blocking.
### `eprint : String -> ()`
Write `s` to stderr. Non-blocking.
### `eprintln : String -> ()`
Write `s` followed by a newline to stderr. Non-blocking.
### `putStr : Int -> String -> ()`
Write `s` to an arbitrary fd. Non-blocking.
### `putStrLn : Int -> String -> ()`
Write `s` followed by a newline to an arbitrary fd. Non-blocking.
### `write : Int -> String -> ()`
`write fd s` is an alias for `putStr fd s`. Kept for when you want
the "I'm emitting bytes, not printing text" shape at the call site.
### `readLine : Option String`
Read one line from stdin, stripping trailing '\n' (and any '\r').
Returns `Some line` or `None` at EOF. Non-blocking — the read runs
on a thread-pool worker.
### `readLineFrom : Int -> Option String`
Read one line from an arbitrary fd. Same semantics as `readLine`.
### `flush : Int -> Bool`
Force pending writes on `fd` to disk / device (`fsync`). Most
io_uring writes are durable on completion so this is rarely needed.
### `isTty : Int -> Bool`
`True` if `fd` is attached to a terminal (as opposed to a pipe or file).
Useful for turning off colored output or prompting prefixes.
### `isatty : Int -> Bool`
Alias for `isTty`, following the libc spelling.
---
# Std\Json
Source: https://yona-lang.org/stdlib/json/
Json -- JSON serialization helpers.
Provides functions to convert Yona values to JSON string fragments
and to parse JSON primitives. Useful for building JSON output or
parsing simple JSON values.
## Functions
### `stringify : Int -> String`
Convert an integer to its JSON string representation.
```yona
import stringify from Std\Json in
stringify 42 # => "42"
```
### `stringifyString : String -> String`
Convert a string to a JSON-quoted string with proper escaping.
```yona
import stringifyString from Std\Json in
stringifyString "hello \"world\"" # => "\"hello \\\"world\\\"\""
```
### `stringifyBool : Bool -> String`
Convert a boolean to `"true"` or `"false"`.
```yona
import stringifyBool from Std\Json in
stringifyBool true # => "true"
```
### `stringifyFloat : Float -> String`
Convert a float to its JSON string representation.
```yona
import stringifyFloat from Std\Json in
stringifyFloat 3.14 # => "3.14"
```
### `null : String`
Returns the JSON null literal string `"null"`.
```yona
import null from Std\Json in
null # => "null"
```
### `parseInt : String -> Int`
Parse a JSON integer string to an Int.
```yona
import parseInt from Std\Json in
parseInt "42" # => 42
```
### `parseFloat : String -> Float`
Parse a JSON float string to a Float.
```yona
import parseFloat from Std\Json in
parseFloat "3.14" # => 3.14
```
---
# Std\List
Source: https://yona-lang.org/stdlib/list/
Sequence (list) operations — map, filter, fold, sort, and more.
All functions operate on sequences (`[1, 2, 3]`). Most are recursive
and work with pattern matching on head|tail (`[h|t]`).
## Functions
### `map : (a -> b) -> [a] -> [b]`
Applies `fn` to every element, returning a new sequence.
```yona
map (\x -> x * 2) [1, 2, 3] # => [2, 4, 6]
map (\x -> x + 1) [] # => []
```
### `filter : (a -> Bool) -> [a] -> [a]`
Keeps only elements where `fn` returns true.
```yona
filter (\x -> x > 2) [1, 2, 3, 4] # => [3, 4]
```
### `fold : (b -> a -> b) -> b -> [a] -> b`
Left fold — reduces a sequence to a single value, left to right.
```yona
fold (\acc x -> acc + x) 0 [1, 2, 3] # => 6
```
### `foldl : (b -> a -> b) -> b -> [a] -> b`
Alias for `fold`.
### `foldr : (a -> b -> b) -> b -> [a] -> b`
Right fold — reduces a sequence right to left.
```yona
foldr (\x acc -> x :: acc) [] [1, 2, 3] # => [1, 2, 3]
```
### `length : [a] -> Int`
Returns the number of elements.
```yona
length [1, 2, 3] # => 3
length [] # => 0
```
### `head : [a] -> Int`
Returns the first element. Crashes on empty sequence.
```yona
head [1, 2, 3] # => 1
```
### `tail : [a] -> [b]`
Returns all elements except the first. Crashes on empty sequence.
```yona
tail [1, 2, 3] # => [2, 3]
```
### `reverse : [a] -> Int`
Reverses the sequence.
```yona
reverse [1, 2, 3] # => [3, 2, 1]
```
### `take : Int -> [a] -> [b]`
Returns the first `n` elements.
```yona
take 2 [1, 2, 3, 4] # => [1, 2]
```
### `drop : Int -> [a] -> [b]`
Drops the first `n` elements.
```yona
drop 2 [1, 2, 3, 4] # => [3, 4]
```
### `flatten : [a] -> [b]`
Flattens a sequence of sequences into a single sequence.
```yona
flatten [[1, 2], [3], [4, 5]] # => [1, 2, 3, 4, 5]
```
### `any : (a -> Bool) -> [a] -> Bool`
Returns `true` if any element satisfies `fn`.
```yona
any (\x -> x > 3) [1, 2, 3, 4] # => true
any (\x -> x > 5) [1, 2, 3] # => false
```
### `all : (a -> Bool) -> [a] -> Bool`
Returns `true` if all elements satisfy `fn`.
```yona
all (\x -> x > 0) [1, 2, 3] # => true
all (\x -> x > 2) [1, 2, 3] # => false
```
### `contains : Int -> [a] -> Bool`
Returns `true` if `elem` is in the sequence.
```yona
contains 3 [1, 2, 3] # => true
contains 5 [1, 2, 3] # => false
```
### `isEmpty : [a] -> Bool`
Returns `true` if the sequence is empty.
```yona
isEmpty [] # => true
isEmpty [1, 2] # => false
```
### `nth : Int -> [a] -> Int`
Returns the element at index `idx` (0-based). Crashes if out of bounds.
```yona
nth 0 [10, 20, 30] # => 10
nth 2 [10, 20, 30] # => 30
```
### `zip : [a] -> [b] -> [c]`
Pairs elements from two sequences. Stops at the shorter one.
```yona
zip [1, 2, 3] [10, 20, 30] # => [(1, 10), (2, 20), (3, 30)]
zip [1, 2] [10] # => [(1, 10)]
```
### `zipWith : (a -> b) -> [a] -> [c] -> [b]`
Combines elements from two sequences using `fn`.
```yona
zipWith (\a b -> a + b) [1, 2, 3] [10, 20, 30] # => [11, 22, 33]
```
### `enumerate : [a] -> [b]`
Pairs each element with its 0-based index.
```yona
enumerate [10, 20, 30] # => [(0, 10), (1, 20), (2, 30)]
```
### `partition : (a -> b) -> [c] -> Int`
Splits into two sequences: elements satisfying `pred` and those that don't.
```yona
partition (\x -> x > 2) [1, 2, 3, 4] # => ([3, 4], [1, 2])
```
### `intersperse : Int -> [a] -> [b]`
Inserts `sep` between every pair of elements.
```yona
intersperse 0 [1, 2, 3] # => [1, 0, 2, 0, 3]
intersperse 0 [1] # => [1]
```
### `scanl : (b -> a -> b) -> b -> [a] -> [b]`
Like `foldl` but returns all intermediate accumulator values.
```yona
scanl (\a b -> a + b) 0 [1, 2, 3] # => [0, 1, 3, 6]
```
### `flatMap : (a -> b) -> [c] -> [d]`
Maps then flattens — applies `fn` which returns a sequence, then concatenates all results.
```yona
flatMap (\x -> [x, x * 10]) [1, 2, 3] # => [1, 10, 2, 20, 3, 30]
```
### `find : (a -> Bool) -> [a] -> Symbol`
Returns `(:some, value)` for the first element satisfying `pred`, or `:none`.
```yona
find (\x -> x > 3) [1, 2, 5, 4] # => (:some, 5)
find (\x -> x > 9) [1, 2, 3] # => :none
```
### `sortBy : (a -> b) -> [a] -> [b]`
Sorts using a comparison function. `cmp a b` should return negative if a < b,
zero if equal, positive if a > b. Uses quicksort.
```yona
sortBy (\a b -> a - b) [3, 1, 4, 1, 5] # => [1, 1, 3, 4, 5]
```
### `groupBy : (a -> b) -> [c] -> Int`
Groups elements by a key function. Returns a sequence of `(key, [values])` pairs.
```yona
groupBy (\x -> x % 2) [1, 2, 3, 4] # => [(1, [1, 3]), (0, [2, 4])]
```
### `sum : [a] -> Int`
Sums all elements (integers).
```yona
sum [1, 2, 3, 4, 5] # => 15
```
### `product : [a] -> Int`
Multiplies all elements (integers).
```yona
product [1, 2, 3, 4, 5] # => 120
```
---
# Std\Log
Source: https://yona-lang.org/stdlib/log/
Log -- leveled logging to stderr.
Provides debug, info, warn, and error log levels with a global
level filter. Messages below the current level are suppressed.
## Functions
### `debug : String -> ()`
Log a message at DEBUG level.
```yona
import debug from Std\Log in
debug "entering function foo"
```
### `info : String -> ()`
Log a message at INFO level.
```yona
import info from Std\Log in
info "server started on port 8080"
```
### `warn : String -> ()`
Log a message at WARN level.
```yona
import warn from Std\Log in
warn "disk usage above 90%"
```
### `error : String -> ()`
Log a message at ERROR level.
```yona
import error from Std\Log in
error "failed to connect to database"
```
### `setLevel : Int -> ()`
Set the global log level. Use 0 = DEBUG, 1 = INFO, 2 = WARN, 3 = ERROR.
```yona
import setLevel from Std\Log in
setLevel 2 # only WARN and ERROR messages will appear
```
### `getLevel : Int`
Returns the current global log level as an integer.
```yona
import getLevel from Std\Log in
getLevel # => 1 (INFO by default)
```
---
# Std\Math
Source: https://yona-lang.org/stdlib/math/
Math — polymorphic numeric operations and float math.
The `Num` trait provides polymorphic `abs`, `max`, `min` for both
Int and Float. Float-specific functions (sqrt, sin, cos, etc.) are
bound from the C math library via extern declarations.
## Traits
### Num
```yona
trait Num a
abs : a -> a
max : a -> a -> a
min : a -> a -> a
negate : a -> a
end
```
Numeric trait — polymorphic over Int and Float.
## Functions
### `abs : a -> a`
### `max : a -> a -> a`
### `min : a -> a -> a`
### `negate : a -> a`
### `clamp : Int -> Int -> Int -> Int`
Restricts a value to the range `[lo, hi]`.
```yona
clamp 0 10 15 # => 10
```
### `sign : Int -> Int`
Returns 1 for positive, -1 for negative, 0 for zero.
```yona
sign 42 # => 1
```
### `isEven : Int -> Bool`
Returns `true` if the integer is even.
### `isOdd : Int -> Bool`
Returns `true` if the integer is odd.
### `gcd : Int -> Int -> Int`
Greatest common divisor (Euclidean algorithm).
```yona
gcd 12 8 # => 4
```
### `pow : Int -> Int -> Int`
Integer exponentiation. Uses fast squaring.
```yona
pow 2 10 # => 1024
```
### `factorial : Int -> Int`
Factorial: `n! = 1 * 2 * ... * n`.
```yona
factorial 5 # => 120
```
### `sqrt : Float -> Float`
Square root (Float -> Float).
### `sin : Float -> Float`
Sine (Float -> Float, radians).
### `cos : Float -> Float`
Cosine (Float -> Float, radians).
### `tan : Float -> Float`
Tangent (Float -> Float, radians).
### `log : Float -> Float`
Natural logarithm (Float -> Float).
### `exp : Float -> Float`
Exponential e^x (Float -> Float).
### `floor : Float -> Float`
Floor (Float -> Float).
### `ceil : Float -> Float`
Ceiling (Float -> Float).
### `round : Float -> Float`
Round to nearest integer (Float -> Float).
### `pi : Float = 3.141592653589793`
Pi constant.
```yona
pi # => 3.14159265358979
```
---
# Std\Net
Source: https://yona-lang.org/stdlib/net/
Net -- TCP and UDP networking with async I/O.
Provides TCP client/server sockets and UDP datagrams. Async operations
(`tcpConnect`, `tcpAccept`, `send`, `recv`, `sendBytes`, `recvBytes`)
use io_uring on Linux for non-blocking I/O.
## Functions
### `tcpConnect : String -> Int -> Int`
Connect to a TCP server. Async (io_uring). Returns a socket descriptor.
```yona
import tcpConnect, send, recv, close from Std\Net in
let sock = tcpConnect "example.com" 80 in
do
send sock "GET / HTTP/1.0\r\nHost: example.com\r\n\r\n"
let resp = recv sock 4096 in
println resp
close sock
end
```
### `tcpListen : String -> Int -> Int`
Create a TCP server socket bound to `host:port`. Returns a listener descriptor.
```yona
import tcpListen, tcpAccept, close from Std\Net in
let server = tcpListen "0.0.0.0" 8080 in
let client = tcpAccept server in
close client
```
### `tcpAccept : Int -> Int`
Accept an incoming TCP connection. Async (io_uring). Returns a client socket descriptor.
### `send : Int -> String -> Int`
Send a string over a socket. Async (io_uring). Returns the number of bytes sent.
### `recv : Int -> Int -> String`
Receive up to `maxBytes` bytes from a socket as a string. Async (io_uring).
### `sendBytes : Int -> ByteArray -> Int`
Send a byte buffer over a socket. Async (io_uring). Returns the number of bytes sent.
### `recvBytes : Int -> Int -> ByteArray`
Receive up to `maxBytes` from a socket as a byte buffer. Async (io_uring).
### `close : Int -> Int`
Close a socket descriptor. Returns 0 on success.
### `udpBind : String -> Int -> Int`
Create a UDP socket bound to `host:port`. Returns a socket descriptor.
```yona
import udpBind, udpRecv, close from Std\Net in
let sock = udpBind "0.0.0.0" 9000 in
let msg = udpRecv sock 1024 in
close sock
```
### `udpSendTo : Int -> String -> Int -> String -> Int`
Send a UDP datagram to `host:port`. Returns the number of bytes sent.
```yona
import udpBind, udpSendTo from Std\Net in
let sock = udpBind "0.0.0.0" 0 in
udpSendTo sock "127.0.0.1" 9000 "hello"
```
### `udpRecv : Int -> Int -> String`
Receive a UDP datagram of up to `maxBytes`. Returns the data as a string.
### `peerAddress : Int -> String`
Returns the remote address of a connected socket as a string.
```yona
import tcpConnect, peerAddress from Std\Net in
let sock = tcpConnect "example.com" 80 in
peerAddress sock # => "93.184.216.34"
```
---
# Std\Option
Source: https://yona-lang.org/stdlib/option/
Optional values — represents a value that may or may not exist.
Use `Some value` to wrap a value, `None` for absence. Chain operations
with `flatMap`, filter with predicates, or provide defaults with `unwrapOr`.
## Types
### Option
`type Option a = Some a | None`
An optional value: either `Some value` or `None`.
## Functions
### `isSome : Option a -> Bool`
Returns `true` if the option contains a value.
```yona
isSome (Some 42) # => true
isSome None # => false
```
### `isNone : Option a -> Bool`
Returns `true` if the option is empty.
```yona
isNone None # => true
isNone (Some 42) # => false
```
### `unwrapOr : a -> Option a -> a`
Extracts the value, or returns `default` if empty.
```yona
unwrapOr 0 (Some 42) # => 42
unwrapOr 0 None # => 0
```
### `map : (a -> b) -> Option a -> Option b`
Transforms the contained value with `fn`, leaving `None` unchanged.
```yona
map (\x -> x * 2) (Some 5) # => Some 10
map (\x -> x * 2) None # => None
```
### `flatMap : (a -> b) -> Option a -> c`
Applies `fn` which itself returns an Option, flattening the result.
Useful for chaining operations that may fail.
```yona
flatMap (\x -> if x > 0 then Some (x * 10) else None) (Some 5) # => Some 50
flatMap (\x -> if x > 0 then Some (x * 10) else None) (Some 0) # => None
```
### `filter : (a -> Bool) -> Option a -> Option a`
Keeps the value only if it satisfies `pred`, otherwise returns `None`.
```yona
filter (\x -> x > 3) (Some 5) # => Some 5
filter (\x -> x > 3) (Some 1) # => None
```
### `orElse : a -> Option a -> Option a`
Returns this option if it contains a value, otherwise returns `alternative`.
```yona
orElse (Some 99) None # => Some 99
orElse (Some 99) (Some 42) # => Some 42
```
### `toResult : a -> Option a -> (b, c)`
Converts to a Result: `Some v` becomes `(:ok, v)`, `None` becomes `(:err, err)`.
```yona
toResult "missing" (Some 42) # => (:ok, 42)
toResult "missing" None # => (:err, "missing")
```
### `zip : Option a -> Option a -> Option a`
Combines two options into an option of a pair. Returns `None` if either is empty.
```yona
zip (Some 1) (Some 2) # => Some (1, 2)
zip (Some 1) None # => None
```
### `fold : a -> (b -> c) -> Option b -> a`
Eliminates an option: returns `onNone` if empty, applies `onSome` if present.
```yona
fold 0 (\x -> x * 10) (Some 5) # => 50
fold 0 (\x -> x * 10) None # => 0
```
---
# Std\Pair
Source: https://yona-lang.org/stdlib/pair/
ADT-based pairs with named fields — an alternative to tuples.
Unlike tuples, `Pair` is a proper ADT with named fields (`fst`, `snd`),
enabling dot access and named pattern matching.
## Types
### Pair
`type Pair a b = Pair { fst : a, snd : b }`
A pair with named fields.
## Functions
### `pair : a -> b -> Pair c d`
Creates a pair from two values.
```yona
pair 1 2 # => Pair { fst = 1, snd = 2 }
```
### `first : Pair a b -> c`
Extracts the first element.
```yona
first (pair 1 2) # => 1
```
### `second : Pair a b -> c`
Extracts the second element.
```yona
second (pair 1 2) # => 2
```
### `mapFirst : (a -> b) -> Pair c d -> Pair e f`
Transforms the first element.
```yona
mapFirst (\x -> x * 10) (pair 3 5) # => Pair { fst = 30, snd = 5 }
```
### `mapSecond : (a -> b) -> Pair c d -> Pair e f`
Transforms the second element.
```yona
mapSecond (\x -> x * 10) (pair 3 5) # => Pair { fst = 3, snd = 50 }
```
### `mapPair : (a -> b) -> (c -> d) -> Pair e f -> Pair g h`
Transforms both elements with two functions.
```yona
mapPair (\x -> x + 1) (\x -> x * 2) (pair 3 5) # => Pair { fst = 4, snd = 10 }
```
### `swap : Pair a b -> Pair c d`
Swaps the two elements.
```yona
swap (pair 1 2) # => Pair { fst = 2, snd = 1 }
```
### `toTuple : Pair a b -> (c, d)`
Converts to a tuple `(a, b)`.
```yona
toTuple (pair 1 2) # => (1, 2)
```
### `fromTuple : (a, b) -> Pair c d`
Creates a pair from a tuple.
```yona
fromTuple (1, 2) # => Pair { fst = 1, snd = 2 }
```
---
# Std\Parallel
Source: https://yona-lang.org/stdlib/parallel/
## Functions
### `pmap : (a -> b) -> [c] -> [b]`
Parallel map — applies `f` to each element concurrently.
All invocations of `f` run in parallel. If any fails, the
rest are cancelled and the error is propagated.
```yona
import pmap from Std\Parallel in
pmap (\x -> x * 2) [1, 2, 3] # => [2, 4, 6]
```
### `pfor : (a -> b) -> [c] -> Int`
Parallel for-each — applies f to each element concurrently
for side effects. Returns the number of elements processed.
---
# Std\Path
Source: https://yona-lang.org/stdlib/path/
Path -- file path manipulation.
Pure string-based path operations for joining, splitting, and
inspecting file paths. No filesystem access is performed.
## Functions
### `join : String -> String -> String`
Join two path components with the platform separator.
```yona
import join from Std\Path in
join "/home/user" "docs" # => "/home/user/docs"
```
### `dirname : String -> String`
Return the directory portion of a path.
```yona
import dirname from Std\Path in
dirname "/home/user/file.txt" # => "/home/user"
```
### `basename : String -> String`
Return the filename portion of a path.
```yona
import basename from Std\Path in
basename "/home/user/file.txt" # => "file.txt"
```
### `extension : String -> String`
Return the file extension including the dot.
```yona
import extension from Std\Path in
extension "photo.jpg" # => ".jpg"
```
### `withExtension : String -> String -> String`
Replace the file extension with a new one.
```yona
import withExtension from Std\Path in
withExtension "data.csv" ".json" # => "data.json"
```
### `isAbsolute : String -> Bool`
Returns `true` if the path is absolute.
```yona
import isAbsolute from Std\Path in
isAbsolute "/usr/bin" # => true
isAbsolute "src/main" # => false
```
---
# Std\Process
Source: https://yona-lang.org/stdlib/process/
Process -- process management, environment, and command execution.
Provides environment variable access, command execution with output
capture, and subprocess management with stdin/stdout pipes. Async
functions (`exec`, `execStatus`, `readAll`, `wait`) block the
current fiber without blocking the OS thread.
## Functions
### `getenv : String -> String`
Get the value of an environment variable. Returns an empty string if not set.
```yona
import getenv from Std\Process in
getenv "HOME" # => "/home/user"
```
### `getcwd : String`
Returns the current working directory.
```yona
import getcwd from Std\Process in
getcwd # => "/home/user/project"
```
### `exit : Int -> Int`
Terminate the process with the given exit code.
```yona
import exit from Std\Process in
exit 0
```
### `exec : String -> String`
Execute a shell command and return its stdout as a string. Async.
```yona
import exec from Std\Process in
let output = exec "ls -la" in
println output
```
### `execStatus : String -> Int`
Execute a shell command and return its exit status code. Async.
```yona
import execStatus from Std\Process in
let code = execStatus "make build" in
println (show code)
```
### `setenv : String -> String -> Int`
Set an environment variable. Returns 0 on success.
```yona
import setenv from Std\Process in
setenv "MY_VAR" "hello"
```
### `hostname : String`
Returns the system hostname.
```yona
import hostname from Std\Process in
hostname # => "myhost"
```
### `spawn : String -> Int`
Spawn a subprocess without waiting for it to finish. Returns a process handle (Int).
```yona
import spawn, wait from Std\Process in
let proc = spawn "sleep 5" in
let status = wait proc in
println (show status)
```
### `readLine : Int -> String`
Read a single line from the subprocess stdout.
```yona
import spawn, readLine from Std\Process in
let proc = spawn "echo hello" in
readLine proc # => "hello"
```
### `readAll : Int -> String`
Read all remaining stdout from a subprocess as a string. Async.
### `wait : Int -> Int`
Wait for a subprocess to exit and return its exit status. Async.
### `kill : Int -> Int -> Int`
Send a signal to a subprocess. Returns 0 on success.
```yona
import spawn, kill from Std\Process in
let proc = spawn "sleep 100" in
kill proc 15 # SIGTERM
```
### `writeStdin : Int -> String -> Int`
Write a string to the subprocess stdin. Returns the number of bytes written.
### `closeStdin : Int -> Int`
Close the stdin pipe of a subprocess. Returns 0 on success.
### `pid : Int -> Int`
Returns the OS process ID of a subprocess.
```yona
import spawn, pid from Std\Process in
let proc = spawn "sleep 10" in
pid proc # => 12345
```
---
# Std\Random
Source: https://yona-lang.org/stdlib/random/
Random -- pseudo-random number generation.
Provides random integers, floats, element selection, and sequence shuffling.
Uses a fast PRNG seeded at program startup. For cryptographically secure
randomness, use `Std.Crypto`.
## Functions
### `int : Int -> Int -> Int`
Generate a random integer in the range `[lo, hi]` (inclusive).
```yona
import int from Std\Random in
int 1 100 # => 42 (random)
```
### `float : Float`
Generate a random float in the range `[0.0, 1.0)`.
```yona
import float from Std\Random in
float # => 0.7312... (random)
```
### `choice : [a] -> Int`
Pick a random element from a sequence. Returns the element.
```yona
import choice from Std\Random in
choice [10, 20, 30] # => 20 (random)
```
### `shuffle : [a] -> [b]`
Return a new sequence with elements in random order.
```yona
import shuffle from Std\Random in
shuffle [1, 2, 3, 4, 5] # => [3, 1, 5, 2, 4] (random)
```
---
# Std\Range
Source: https://yona-lang.org/stdlib/range/
Integer ranges with optional step — lazy representation, materialized on demand.
Ranges are represented as `(:range, start, stop, step)` tuples.
They don't allocate a sequence until `toList` is called.
## Functions
### `range : Int -> Int -> (a, b)`
Creates a range from `start` to `stop` (inclusive) with step 1.
```yona
toList (range 1 5) # => [1, 2, 3, 4, 5]
```
### `rangeStep : Int -> Int -> Int -> (a, b)`
Creates a range from `start` to `stop` with a custom `step`.
```yona
toList (rangeStep 0 10 3) # => [0, 3, 6, 9]
toList (rangeStep 10 0 (0 - 2)) # => [10, 8, 6, 4, 2, 0]
```
### `toList : (a, b) -> [c]`
Materializes the range into a sequence.
```yona
toList (range 1 3) # => [1, 2, 3]
```
### `contains : Int -> (a, b) -> Bool`
Returns `true` if `value` falls within the range and aligns with the step.
```yona
contains 3 (range 1 5) # => true
contains 3 (rangeStep 0 10 2) # => false (0, 2, 4, 6, 8, 10)
```
### `length : (a, b) -> Int`
Returns the number of elements in the range.
```yona
length (range 1 10) # => 10
```
### `take : Int -> (a, b) -> (c, d)`
Returns a range containing only the first `n` elements.
```yona
toList (take 3 (range 1 10)) # => [1, 2, 3]
```
### `drop : Int -> (a, b) -> (c, d)`
Returns a range with the first `n` elements removed.
```yona
toList (drop 3 (range 1 5)) # => [4, 5]
```
### `map : (a -> b) -> (c, d) -> [b]`
Applies `fn` to each element, returning a sequence (not a range).
```yona
map (\x -> x * x) (range 1 4) # => [1, 4, 9, 16]
```
### `filter : (a -> Bool) -> (b, c) -> [a]`
Keeps only elements satisfying `pred`, returning a sequence.
```yona
filter (\x -> x % 2 == 0) (range 1 6) # => [2, 4, 6]
```
### `fold : (a -> b) -> Int -> (c, d) -> Int`
Left fold over the range.
```yona
fold (\acc x -> acc + x) 0 (range 1 5) # => 15
```
### `forEach : (a -> b) -> (c, d) -> Symbol`
Applies `fn` to each element for side effects.
```yona
forEach (\x -> print x) (range 1 3) # prints 1, 2, 3
```
---
# Std\Regex
Source: https://yona-lang.org/stdlib/regex/
Regex — PCRE2-backed regular expressions.
```yona
let re = compile "[a-z]+" in
matches re "hello 123"
```
## Functions
### `compile : String -> Int`
### `matches : Int -> String -> Bool`
### `find : Int -> String -> Seq`
### `findAll : Int -> String -> Seq`
### `replace : Int -> String -> String -> String`
### `replaceAll : Int -> String -> String -> String`
### `split : Int -> String -> Seq`
---
# Std\Result
Source: https://yona-lang.org/stdlib/result/
Error handling — represents either success (`Ok value`) or failure (`Err error`).
Chain operations with `flatMap`/`andThen`, transform errors with `mapErr`,
or extract values with `unwrapOr`. Convert to Option with `toOption`.
## Types
### Result
`type Result a e = Ok a | Err e`
A result type: either `Ok value` (success) or `Err error` (failure).
## Functions
### `isOk : Result a b -> Bool`
Returns `true` if the result is `Ok`.
```yona
isOk (Ok 42) # => true
isOk (Err "fail") # => false
```
### `isErr : Result a b -> Bool`
Returns `true` if the result is `Err`.
```yona
isErr (Err "fail") # => true
isErr (Ok 42) # => false
```
### `unwrapOr : a -> Result b c -> d`
Extracts the value from `Ok`, or returns `default` if `Err`.
```yona
unwrapOr 0 (Ok 42) # => 42
unwrapOr 0 (Err "fail") # => 0
```
### `map : (a -> b) -> Result c d -> Result e f`
Transforms the success value, leaving errors unchanged.
```yona
map (\x -> x * 2) (Ok 21) # => Ok 42
map (\x -> x * 2) (Err "fail") # => Err "fail"
```
### `mapErr : (a -> b) -> Result c d -> Result e f`
Transforms the error value, leaving successes unchanged.
```yona
mapErr (\e -> e + "!") (Err "fail") # => Err "fail!"
mapErr (\e -> e + "!") (Ok 42) # => Ok 42
```
### `flatMap : (a -> b) -> Result c d -> e`
Applies `fn` which returns a Result, flattening the nested result.
```yona
flatMap (\x -> if x > 0 then Ok (x * 2) else Err "negative") (Ok 21) # => Ok 42
flatMap (\x -> Ok (x * 2)) (Err "fail") # => Err "fail"
```
### `flatten : Result a b -> Result c d`
Flattens a nested `Result (Result a e) e` into `Result a e`.
```yona
flatten (Ok (Ok 42)) # => Ok 42
flatten (Ok (Err "inner")) # => Err "inner"
flatten (Err "outer") # => Err "outer"
```
### `toOption : Result a b -> (c, d)`
Converts to a symbol-tagged option: `Ok v` → `(:some, v)`, `Err _` → `:none`.
```yona
toOption (Ok 42) # => (:some, 42)
toOption (Err "fail") # => :none
```
### `andThen : (a -> b) -> Result c d -> e`
Alias for `flatMap` — chains a computation that may fail.
```yona
andThen (\x -> Ok (x + 1)) (Ok 41) # => Ok 42
```
### `orElse : (a -> b) -> Result c d -> Result e f`
Recovers from an error by applying `fn` to the error value.
```yona
orElse (\e -> Ok 0) (Err "fail") # => Ok 0
orElse (\e -> Ok 0) (Ok 42) # => Ok 42
```
### `fold : (a -> b) -> (c -> d) -> Result e f -> g`
Eliminates a result: applies `onErr` to errors, `onOk` to successes.
```yona
fold (\e -> 0) (\v -> v * 2) (Ok 21) # => 42
fold (\e -> 0) (\v -> v * 2) (Err "fail") # => 0
```
---
# Std\Set
Source: https://yona-lang.org/stdlib/set/
Set — persistent set backed by a Hash Array Mapped Trie (HAMT).
Provides immutable sets with O(log32 n) insert, membership test, and
standard set operations (union, intersection, difference). Iterators
use stack-based trie traversal with O(1) memory per element.
## Functions
### `insert : Set a -> a -> Set a`
Add an element to the set. Returns a new set containing `elem`.
The original set is unchanged. Inserting a duplicate is a no-op.
```yona
let s = insert (insert #{} 1) 2 in
size s # => 2
```
### `contains : Set a -> a -> Bool`
Check whether `elem` is a member of the set.
```yona
let s = insert #{} 42 in
contains s 42 # => true
contains s 99 # => false
```
### `size : Set a -> Int`
Returns the number of elements in the set.
```yona
let s = insert (insert #{} 1) 2 in
size s # => 2
```
### `elements : Set a -> [a]`
Eagerly collects all elements into a sequence.
```yona
let s = insert (insert #{} 3) 1 in
elements s # => [3, 1] (order may vary)
```
### `union : Set a -> Set a -> Set a`
Returns a new set containing all elements from both `a` and `b`.
```yona
let a = insert (insert #{} 1) 2 in
let b = insert (insert #{} 2) 3 in
elements (union a b) # => [1, 2, 3] (order may vary)
```
### `intersection : Set a -> Set a -> Set a`
Returns a new set containing only elements present in both `a` and `b`.
```yona
let a = insert (insert #{} 1) 2 in
let b = insert (insert #{} 2) 3 in
elements (intersection a b) # => [2]
```
### `difference : Set a -> Set a -> Set a`
Returns a new set containing elements in `a` that are not in `b`.
```yona
let a = insert (insert (insert #{} 1) 2) 3 in
let b = insert #{} 2 in
elements (difference a b) # => [1, 3] (order may vary)
```
### `iterator : Set a -> Iterator a`
Returns a streaming `Iterator Int` over set elements.
Uses stack-based trie traversal — O(1) memory per element.
```yona
import iterator from Std\Set in
let s = insert (insert #{} 1) 2 in
let iter = iterator s in
# consume with iterator protocol
```
### `forEach : (a -> b) -> Set a -> ()`
Apply `callback` to each element for side effects.
```yona
let s = insert (insert #{} 1) 2 in
forEach (\x -> println (show x)) s
```
---
# Std\String
Source: https://yona-lang.org/stdlib/string/
String -- string manipulation and conversion.
Provides utilities for searching, transforming, splitting, and
converting strings. Iterator-returning functions (`split`, `lines`,
`chars`) use O(1) memory per element.
## Functions
### `length : String -> Int`
Returns the length of the string in bytes.
```yona
import length from Std\String in
length "hello" # => 5
```
### `isEmpty : String -> Bool`
Returns `true` if the string has zero length.
```yona
import isEmpty from Std\String in
isEmpty "" # => true
isEmpty "hi" # => false
```
### `toUpperCase : String -> String`
Convert all characters to uppercase.
```yona
import toUpperCase from Std\String in
toUpperCase "hello" # => "HELLO"
```
### `toLowerCase : String -> String`
Convert all characters to lowercase.
```yona
import toLowerCase from Std\String in
toLowerCase "HELLO" # => "hello"
```
### `trim : String -> String`
Remove leading and trailing whitespace.
```yona
import trim from Std\String in
trim " hello " # => "hello"
```
### `indexOf : String -> String -> Int`
Return the index of the first occurrence of `needle`, or -1 if not found.
```yona
import indexOf from Std\String in
indexOf "hello world" "world" # => 6
```
### `contains : String -> String -> Bool`
Returns `true` if `str` contains `needle`.
```yona
import contains from Std\String in
contains "hello world" "world" # => true
```
### `startsWith : String -> String -> Bool`
Returns `true` if `str` starts with `prefix`.
```yona
import startsWith from Std\String in
startsWith "hello" "hel" # => true
```
### `endsWith : String -> String -> Bool`
Returns `true` if `str` ends with `suffix`.
```yona
import endsWith from Std\String in
endsWith "hello.txt" ".txt" # => true
```
### `substring : String -> Int -> Int -> String`
Extract a substring from index `start` (inclusive) to `end` (exclusive).
```yona
import substring from Std\String in
substring "hello" 1 4 # => "ell"
```
### `replace : String -> String -> String -> String`
Replace all occurrences of `old` with `new`.
```yona
import replace from Std\String in
replace "aabaa" "a" "x" # => "xxbxx"
```
### `split : String -> String -> Iterator a`
Split a string by a delimiter. Returns an `Iterator String`.
```yona
import split from Std\String in
let iter = split "a,b,c" "," in
# consume with iterator protocol
```
### `join : String -> [a] -> String`
Join a sequence of strings with a separator.
```yona
import join from Std\String in
join ", " ["a", "b", "c"] # => "a, b, c"
```
### `charAt : String -> Int -> Int`
Returns the character code (Int) at the given index.
```yona
import charAt from Std\String in
charAt "ABC" 0 # => 65
```
### `padLeft : Int -> String -> String -> String`
Pad `str` on the left with `pad` until it reaches `width`.
```yona
import padLeft from Std\String in
padLeft 5 "0" "42" # => "00042"
```
### `padRight : Int -> String -> String -> String`
Pad `str` on the right with `pad` until it reaches `width`.
```yona
import padRight from Std\String in
padRight 5 "." "hi" # => "hi..."
```
### `reverse : String -> String`
Reverse a string.
```yona
import reverse from Std\String in
reverse "hello" # => "olleh"
```
### `repeat : Int -> String -> String`
Repeat a string `n` times.
```yona
import repeat from Std\String in
repeat 3 "ab" # => "ababab"
```
### `take : Int -> String -> String`
Take the first `n` characters of a string.
```yona
import take from Std\String in
take 3 "hello" # => "hel"
```
### `drop : Int -> String -> String`
Drop the first `n` characters of a string.
```yona
import drop from Std\String in
drop 3 "hello" # => "lo"
```
### `count : String -> String -> Int`
Count the number of non-overlapping occurrences of `needle` in `str`.
```yona
import count from Std\String in
count "ababa" "ab" # => 2
```
### `lines : String -> Iterator a`
Split a string into lines. Returns an `Iterator String`.
```yona
import lines from Std\String in
let iter = lines "a\nb\nc" in
# consume with iterator protocol
```
### `unlines : [a] -> String`
Join a sequence of strings with newline separators.
```yona
import unlines from Std\String in
unlines ["a", "b", "c"] # => "a\nb\nc"
```
### `chars : String -> Iterator a`
Returns an `Iterator` over individual characters of the string.
```yona
import chars from Std\String in
let iter = chars "hello" in
# consume with iterator protocol
```
### `fromChars : [a] -> String`
Build a string from a sequence of character codes.
```yona
import fromChars from Std\String in
fromChars [72, 105] # => "Hi"
```
### `toInt : String -> Int`
Parse a string as an integer.
```yona
import toInt from Std\String in
toInt "42" # => 42
```
### `toFloat : String -> Float`
Parse a string as a float.
```yona
import toFloat from Std\String in
toFloat "3.14" # => 3.14
```
---
# Std\Task
Source: https://yona-lang.org/stdlib/task/
Task spawning for concurrent execution.
## Functions
### spawn
```yona
spawn : (() -> a) -> a
```
Spawn a Yona closure as a concurrent task on a thread pool worker.
Returns a promise that resolves to the closure's return value when the
task completes.
`spawn` is declared as an `IO` function — its result is auto-awaited at
the value's first use, just like `readFile` and other I/O calls. This
means the existing transparent async machinery handles task lifecycle:
```yona
import spawn from Std\Task in
let
a = spawn (\() -> compute1 ()), -- runs concurrently
b = spawn (\() -> compute2 ()) -- runs concurrently
in a + b -- auto-awaits both
```
The let-binding auto-grouping mechanism (structured concurrency) treats
both spawn calls as parallel tasks. They submit immediately, run on
separate worker threads, and the let body waits for both before computing
`a + b`.
## Combining with Channels
The typical pattern is producer-consumer via `Std\Channel`:
```yona
import channel, send, recv, close from Std\Channel in
import spawn from Std\Task in
with ch = channel 16 in
let _ = spawn (\() ->
-- producer: send values, then close
let _ = send ch 1 in
let _ = send ch 2 in
close ch
) in
-- consumer (main task): receive until None
let loop acc = case recv ch of
Some v -> loop (acc + v)
None -> acc
end in
loop 0
end
```
The producer runs on a worker thread; the main task reads from the
channel. When the channel is full, the producer's worker blocks until
the consumer drains some. When the channel is empty, the consumer
blocks until the producer sends more or closes.
## Implementation Notes
- Backed by `yona_rt_async_spawn_closure` in the runtime
- The closure runs on the next available thread pool worker (8 threads by default)
- The promise is fulfilled when the closure returns
- Exceptions from the spawned closure propagate to the awaiting task
- Compatible with structured concurrency (task group cancellation)
---
# Std\Test
Source: https://yona-lang.org/stdlib/test/
Simple test assertions — returns `(:pass, name)` or `(:fail, message)`.
Each assertion returns a symbol-tagged tuple so test runners can
collect results programmatically.
## Functions
### `assertEqual : Int -> Int -> (a, b)`
Asserts that `expected` equals `actual`.
```yona
assertEqual 42 42 # => (:pass, "assertEqual")
assertEqual 1 2 # => (:fail, "assertEqual: expected equal values")
```
### `assertNotEqual : Int -> Int -> (a, b)`
Asserts that `expected` does not equal `actual`.
```yona
assertNotEqual 1 2 # => (:pass, "assertNotEqual")
```
### `assertTrue : Int -> (a, b)`
Asserts that `value` is true.
```yona
assertTrue (1 > 0) # => (:pass, "assertTrue")
```
### `assertFalse : Int -> (a, b)`
Asserts that `value` is false.
```yona
assertFalse (1 > 2) # => (:pass, "assertFalse")
```
### `assertGreater : Int -> Int -> (a, b)`
Asserts that `a > b`.
```yona
assertGreater 5 3 # => (:pass, "assertGreater")
```
### `assertLess : Int -> Int -> (a, b)`
Asserts that `a < b`.
```yona
assertLess 3 5 # => (:pass, "assertLess")
```
---
# Std\Time
Source: https://yona-lang.org/stdlib/time/
Time -- timestamps, sleeping, and elapsed time measurement.
Provides monotonic and wall-clock timestamps in milliseconds
and microseconds, sleep, and formatted time output.
## Functions
### `now : Int`
Returns the current wall-clock time in milliseconds since the Unix epoch.
```yona
import now from Std\Time in
now # => 1712678400000
```
### `nowMicros : Int`
Returns the current time in microseconds since the Unix epoch.
```yona
import nowMicros from Std\Time in
nowMicros # => 1712678400000000
```
### `epoch : Int`
Returns the Unix epoch (0) as a timestamp. Useful as a base for relative calculations.
```yona
import epoch from Std\Time in
epoch # => 0
```
### `sleep : Int -> ()`
Sleep for the given number of milliseconds.
```yona
import sleep from Std\Time in
sleep 1000 # sleep for 1 second
```
### `format : Int -> String`
Format a millisecond timestamp as a human-readable date-time string.
```yona
import now, format from Std\Time in
format (now) # => "2025-04-09 12:00:00"
```
### `elapsed : Int -> Int -> Int`
Compute the elapsed time in milliseconds between two timestamps.
```yona
import now, elapsed, sleep from Std\Time in
let t0 = now in
do
sleep 100
let t1 = now in
elapsed t0 t1 # => ~100
end
```
---
# Std\Tuple
Source: https://yona-lang.org/stdlib/tuple/
Operations on 2-tuples (pairs).
Tuples are the built-in product type `(a, b)`. This module provides
accessors, transformers, and conversion functions.
## Functions
### `fst : (a, b) -> Int`
Returns the first element of a pair.
```yona
fst (1, 2) # => 1
```
### `snd : (a, b) -> Int`
Returns the second element of a pair.
```yona
snd (1, 2) # => 2
```
### `swap : (a, b) -> (c, d)`
Swaps the elements of a pair.
```yona
swap (1, 2) # => (2, 1)
```
### `mapBoth : (a -> b) -> (c -> d) -> (e, f) -> (g, h)`
Applies two functions to the respective elements.
```yona
mapBoth (\x -> x + 1) (\x -> x * 2) (3, 5) # => (4, 10)
```
### `mapFst : (a -> b) -> (c, d) -> (e, f)`
Transforms the first element, keeping the second unchanged.
```yona
mapFst (\x -> x * 10) (3, 5) # => (30, 5)
```
### `mapSnd : (a -> b) -> (c, d) -> (e, f)`
Transforms the second element, keeping the first unchanged.
```yona
mapSnd (\x -> x * 10) (3, 5) # => (3, 50)
```
### `toList : (a, b) -> [c]`
Converts a pair to a two-element sequence.
```yona
toList (1, 2) # => [1, 2]
```
### `curry : (a -> b) -> Int -> Int -> (c, d)`
Converts a function taking a pair into one taking two arguments.
```yona
let add = \(a, b) -> a + b in curry add 3 4 # => 7
```
### `uncurry : (a -> b) -> (c, d) -> Int`
Converts a function taking two arguments into one taking a pair.
```yona
let add = \a b -> a + b in uncurry add (3, 4) # => 7
```
---
# Std\Types
Source: https://yona-lang.org/stdlib/types/
Types -- runtime type conversions.
Provides functions to convert between Yona's primitive types:
Int, Float, Bool, and String.
## Functions
### `toInt : String -> Int`
Parse a string as an integer.
```yona
import toInt from Std\Types in
toInt "42" # => 42
```
### `toFloat : String -> Float`
Parse a string as a float.
```yona
import toFloat from Std\Types in
toFloat "3.14" # => 3.14
```
### `intToString : Int -> String`
Convert an integer to its string representation.
```yona
import intToString from Std\Types in
intToString 42 # => "42"
```
### `floatToString : Float -> String`
Convert a float to its string representation.
```yona
import floatToString from Std\Types in
floatToString 3.14 # => "3.14"
```
### `boolToString : Bool -> String`
Convert a boolean to `"true"` or `"false"`.
```yona
import boolToString from Std\Types in
boolToString true # => "true"
```
---
# Why Yona 2.0
Source: https://yona-lang.org/why-yona-2/
Yona 2.0 is a ground-up reimplementation of the Yona language: a native,
ahead-of-time compiler built on LLVM, with a static type system. It replaces
the original GraalVM-hosted interpreter. This chapter explains the decision
honestly — what the first design got right, why its foundation stopped
fitting, and what changed.
## What Yona 1.x was
Yona began in 2018 as a dynamically typed, strict functional language for the
GraalVM: minimal ML-like syntax, few expression forms, and one founding idea —
**transparent concurrency**. Programs never mentioned promises or callbacks;
the runtime analyzed `let` expressions, batched independent bindings, and ran
them in parallel over non-blocking I/O. Persistent sequences, dictionaries,
and sets were built in, with full pattern-matching support.
Hosting on GraalVM/Truffle was a sound bet at the time. A small team got a
world-class JIT, garbage collection, and polyglot interoperability with Java
and JavaScript without writing a compiler backend from scratch. Yona 0.8.x
shipped, worked, and found its voice. The
[GraalVM implementation](https://github.com/yona-lang/yona) remains available
in that form, and its original documentation is preserved at
[yona-lang.github.io](https://yona-lang.github.io/).
## Why GraalVM stopped fitting
Five pressures accumulated, and each pointed away from the JVM.
**API instability.** Truffle and the Graal compiler interfaces moved fast and
broke often. For a large language team that churn is absorbable; for a small
language it converted every GraalVM upgrade into a rewrite tax, paid out of
the budget that should have gone to the language itself. Yona's interfaces to
its own users were stable; its foundation was not.
**The JVM as product surface.** Installing Yona 1.x meant installing GraalVM,
adding a component JAR with `gu`, and accepting JVM startup time and memory
floors. A language whose pitch is simplicity cannot require a virtual machine
distribution as a prerequisite. Yona 2.0 installs with
`dnf install yona`, `apt install yona`, `brew install akovari/tap/yona`, or a
Windows MSI — and compiles programs to self-contained native executables.
**The dynamic ceiling.** Yona 1.x was proudly dynamic, and honest about the
consequences: ADTs were conventions over tuples and symbols, there was no
exhaustiveness checking, and what other languages solve with type classes had
to be solved "by convention of sorts". That ceiling was fine for scripts and
increasingly wrong for the systems Yona wanted to serve — and it made
machine-generated code impossible to verify beyond "it parses".
**The performance model.** A tracing JIT accelerates hot interpreter loops;
it does not give you native binaries, predictable ahead-of-time performance,
deterministic memory behavior, or a path to lowering array pipelines onto a
GPU. LLVM gives all four.
**Polyglot cost versus value.** GraalVM's headline feature — calling Java and
JavaScript from Yona — was rarely the reason anyone chose the language. It was
paid for continuously and used occasionally. Yona 2.0 replaces it with a
plain C FFI (`extern` declarations), which is smaller, stable, and sufficient.
## What 2.0 keeps
The rewrite preserved everything that made Yona feel like Yona:
- **The syntax.** Juxtaposition application, few expression forms
(`let`, `do`, `case`, `if`, `with`, `try`/`catch` + `raise`, `import`,
`module`), significant newlines, no boilerplate.
- **Transparent concurrency.** Independent `let` bindings still parallelize
automatically; `do` still sequences; `with` still scopes resources. The
machinery underneath is now io_uring and a work-stealing thread pool
instead of Truffle promises — the programming model is unchanged.
- **Persistent data structures.** Sequences, dictionaries, and sets with
structural sharing, now implemented as radix-balanced tries and HAMTs in
native code.
- **Pattern matching everywhere**, including head-tail decomposition,
or-patterns, guards, and `as` bindings.
## What 2.0 adds
**A native pipeline.** Source → typed AST → LLVM IR → machine code. Common
benchmarks land within 1–2× of C; collection pipelines are stream-fused into
single loops. See [Performance](/guides/performance/) for methodology and
numbers.
**A static type system.** Hindley–Milner inference means programs are fully
typed with almost no annotations. On top of inference: algebraic data types
with exhaustive matching, traits (type classes) resolved by monomorphization,
record-row polymorphism, and **effect rows** — a function's arrow carries the
effects it may perform (`Int -> !{State.get} Int`), checked at call sites.
Linear types track resources such as file handles, sockets, and channel
endpoints, so leaking one is a compile error. Some of this is complete, some
is honestly partial; every feature page carries a status badge, and
[The type system](/guides/type-system/) states precisely what is checked
today.
**Memory management that matches the runtime.** Atomic reference counting
with Perceus-style ownership transfer, uniqueness-based in-place updates, and
escape analysis for arena allocation — no garbage collector, no pauses, no
JVM heap.
**Distribution.** Copr, PPA, AUR, Homebrew, Windows MSI. One binary compiler
(`yonac`), one REPL (`yona`), no VM.
**Accelerators.** `Std\GPU` executes columnar map/filter/reduce pipelines on
Vulkan compute queues, and the compiler can lower ordinary `IntArray` /
`FloatArray` pipelines to it transparently. This was structurally impossible
on the old stack. See [Accelerators](/guides/accelerators/).
## What was left behind
Honesty requires the other list. Yona 2.0 does **not** carry over:
- **GraalVM polyglot interop.** Calling Java or JavaScript is gone; the FFI
is C (`extern` declarations).
- **Software transactional memory.** STM was a 1.x flagship module. It is on
the 2.0 backlog, not in the language today.
- **First-class module values.** In 1.x, modules were runtime values you
could create dynamically. In 2.0, modules are compile-time units with
`.yonai` interface files that enable separate compilation and cross-module
generics. This is a real semantic break, traded for static checking and
native linking.
## Who Yona 2.0 is for
Yona 2.0 is for people who want a small functional language that compiles,
types, and runs like systems software: no async/await ceremony, no VM, no
garbage collector — and for a world in which much code is written by
machines, a compiler strict enough to keep that code honest.
Continue with the [quick start](/learn/quick-start/), or read how the
[concurrency model](/learn/concurrency/) works.