Agent Reference
Dense, example-heavy reference for AI coding agents working with Eucalypt. All content verified against source. See the guide chapters for narrative explanations.
1. Syntax Reference
Section titled “1. Syntax Reference”1.1 Primitives
Section titled “1.1 Primitives”| Type | Syntax | Examples |
|---|---|---|
| Integer | digits | 42, -7, 0 |
| Float | digits with . |
3.14, -0.5 |
| String | "..." |
"hello" |
| Raw string | r"..." |
r"C:\path", r"^\d+" |
| C-string | c"..." |
c"line\nbreak", c"tab\there" |
| T-string (ZDT) | t"..." |
t"2024-03-15", t"2024-03-15T14:30:00Z" |
| Symbol | :name |
:key, :active |
| Boolean | literals | true, false |
| Null | literal | null |
String escape sequences (c-strings only): \n newline, \t tab,
\r carriage return, \\ backslash, \" quote, \{ \} literal
braces, \xHH hex byte, \uHHHH unicode, \UHHHHHHHH extended
unicode.
String interpolation (all string types except t-strings): embed
expressions with {expr}. Literal braces via {{ and }}. Format
specifiers: {value:%.2f}, {n:%06d}.
Raw strings treat backslashes literally but still support {}
interpolation.
1.2 Collections
Section titled “1.2 Collections”# List (commas required)[1, 2, 3][][1, "two", :three, true]
# Block (commas optional){ a: 1 b: 2 c: 3 }{ a: 1, b: 2, c: 3 }1.3 Declarations
Section titled “1.3 Declarations”| Form | Syntax | Notes |
|---|---|---|
| Property | name: expr |
Defines a named value, rendered in output |
| Function | f(x, y): expr |
Not rendered in output |
| List destructure | f([a, b]): expr |
Single param, list destructured |
| Block destructure | f({x y}): expr |
Single param, block destructured |
| Cons destructure | f([h : t]): expr |
Single param, head/tail split |
| Juxtaposed list | f[a, b]: expr |
Sugar for f([a, b]): expr |
| Juxtaposed block | f{x y}: expr |
Sugar for f({x y}): expr |
| Binary operator | (l op r): expr |
Symbolic name required |
| Prefix operator | (op x): expr |
Unary prefix |
| Postfix operator | (x op): expr |
Unary postfix |
Top-level unit: the file itself is an implicit block without braces.
1.3.1 Idiot Brackets
Section titled “1.3.1 Idiot Brackets”Idiot brackets are user-definable Unicode bracket pairs. Inside the brackets, whitespace-separated items are collected into a list and passed as the single argument to the function named by the bracket pair’s declaration.
# Declare a bracket pair function (xs receives the item list)⟦ xs ⟧: xs map(_ * 2)
# Usage — items are collected as a list⟦ 3 4 5 ⟧ # => [6, 8, 10]Any matching Unicode bracket pair can be declared. The prelude defines two bracket pairs for rounding:
⌈ x ⌉: x ceiling # prelude: ceiling bracket⌊ x ⌋: x floor # prelude: floor bracket
⌈3.2⌉ # => 4⌊3.8⌋ # => 3⌈-1.5⌉ # => -1⌊-1.5⌋ # => -2Bracket parameter pattern: the declaration’s parameter is always the list of collected items. Use destructuring when the bracket expects a fixed structure:
# Idiom bracket: first item is a function, rest are argument lists⌈ [f: lists] ⌉: foldl(zapp, repeat(f), lists)Juxtaposed call syntax after a bracket expression: a bracket
expression can be followed immediately by [args] or {block} to
juxtapose-call the result. This is valid syntax (a parser fix ensures
it works):
# ⌈expr⌉[args] — evaluate the bracket, then call with list argument⌈ g ⌉[xs]
# ⌈expr⌉{block} — evaluate the bracket, then call with block argument⌈ h ⌉{x: 1}Monadic brackets: when a bracket pair is declared with :monad
metadata, it acts as monadic do-notation. Items inside the brackets
are bind steps (name: action); the return expression follows the
closing bracket as .name or .(expr):
# List monad declared with ⌈⌉⌈{}⌉: { :monad bind(m, f): m mapcat(f) return(v): [v] }
# Usage: cartesian product⌈ x: [1, 2] y: [10, 20] ⌉.(x + y) # => [11, 21, 12, 22]Monadic brackets cannot be empty — at least one bind step is required (an empty monadic block is a desugaring error).
Path bracket shorthand (‹›): lib/lens.eu defines ‹› as a
bracket that converts a sequence of symbols and numbers into a
composed lens path:
{ import: "lens.eu" }‹:server :db :host› # same as at(:server) ∘ at(:db) ∘ at(:host)‹:items 0 :title› # at(:items) ∘ ix(0) ∘ at(:title)1.4 Comments
Section titled “1.4 Comments”# Line comment (to end of line)x: 42 # inline comment1.5 Metadata Annotations
Section titled “1.5 Metadata Annotations”Placed between a leading backtick and the declaration:
# Documentation shorthand (string = doc metadata)` "Adds two numbers"add(x, y): x + y
# Structured metadata` { doc: "Deep merge operator" associates: :left precedence: :append }(l << r): deep-merge(l, r)
# Suppress from output` :suppresshelper(x): x + 1
# Export target (any bare symbol is a target shortcut)` :my-outputoutput: { result: 42 }
# Target using the declaration's own name` :targetreport: { total: 42 }
# Mark as main (default) target` :mainmain: { result: 42 }
# Mark as unit-internal (invisible to importers and output)` :internalhelper(x): x + 1
# Structured form of internal visibility` { export: :internal }another-helper(x): x * 2Declaration visibility (export:): controls whether a declaration
appears in rendered output and is visible to importers:
| Value | Rendered | Visible to importers | Shorthand |
|---|---|---|---|
:normal (default) |
yes | yes | — |
:suppress |
no | yes | ` :suppress |
:internal |
no | no | ` :internal |
:internal makes a binding completely private to its unit — it stays
accessible to sibling declarations within the same file but is invisible
to any importing unit and absent from rendered output. Two units with
same-named internal helpers do not conflict.
Unit-level metadata: if the first item in a file is an expression (not a declaration), it becomes metadata for the entire unit:
{ import: "helpers.eu" }result: helper(42)Unit metadata keys:
| Key | Value | Effect |
|---|---|---|
import |
string or list | Import files/resources |
requires |
semver string | Fail at load time if version doesn’t match |
prelude |
string path | Use an alternative prelude |
doc |
string | Unit documentation |
# Version pinning — checked at load time, before evaluation{ requires: ">=0.8" import: "helpers.eu" }result: helper(42)
# Alternative prelude{ prelude: "my-prelude.eu" }x: custom-fn(1)Trace metadata: annotate declarations to trace entry arguments and/or exit values to stderr during evaluation:
# Lazy entry trace — shows <thunk> for unevaluated args` :tracef(x, y): some-pipeline x y# stderr: → f(x: <thunk>, y: <thunk>)
# Strict entry trace — forces args to WHNF before printing` { trace: :strict }f(x, y): some-pipeline x y# stderr: → f(x: 42, y: [1, 2, 3])
# Entry + exit trace (lazy)` { trace: :exit }f(x, y): some-pipeline x y# stderr: → f(x: <thunk>, y: <thunk>)# stderr: ← f: <thunk>
# Entry + exit trace (strict) — forces both args and result` { trace: :strict-exit }f(x, y): some-pipeline x y# stderr: → f(x: 42, y: [1, 2, 3])# stderr: ← f: 3Trace output goes to stderr and does not affect the program’s result.
Lazy mode (:trace, :exit) never forces evaluation — it peeks at
values that have already been evaluated. Strict mode (:strict,
:strict-exit) forces arguments/results to WHNF, which changes
evaluation order.
Deprecation metadata: mark declarations as deprecated to generate compile-time warnings:
# Bare deprecation` :deprecatedold-fn(x): x + 1
# With message` { deprecated: "use new-fn instead" }old-fn(x): x + 1
# With replacement pointer (enables LSP quick-fix)` { deprecated: "use new-fn instead" replaced-by: "new-fn" }old-fn(x): x + 1Referencing a deprecated declaration emits a warning on stderr.
Under eu check --strict, deprecation warnings become errors.
Deprecated declarations still work — deprecation is advisory.
A top-level declaration is matched by its bare name; a declaration nested in a
namespace block is matched by the dotted path a caller writes (state.exec),
so both io.exec and an unrelated top-level exec stay silent. A reference
counts only when it resolves to the declaration, so a lambda parameter called
state and a local { state: … }.( … ) block are both silent, as is a nested
declaration referenced by its bare name from inside its own block. The residual
case that still matches by name alone is a top-level block of your own sharing a
deprecated library namespace’s name.
Type annotations (optional, advisory): add type: alongside doc:
to annotate declarations for the type checker (eu check):
` { doc: "`double(x)` - double a number." type: "number -> number" }double(x): x * 2
` { doc: "`map(f, xs)` - apply f to each element." type: "(a -> b) -> [a] -> [b]" }map: __MAPType aliases: define reusable type names in unit metadata or via
type-def: / result-def: on a declaration:
# Named aliases in unit metadata{ types: { Point: "{x: number, y: number}" Person: "{name: string, age: number, email: string | null, ..}" } }
# Alias using binding name (shorthand — `:type-def` or `type-def: true`)` :type-deforigin: { x: 0, y: 0 }# Registers alias `origin` = the binding's type
# Alias with an explicit name` { type-def: "Point" }origin: { x: 0, y: 0 }# Registers alias `Point` = the binding's type
# Return-type alias for a constructor function` { result-def: "Count" type: "string → number" }char-count(s): str.length(s)# Registers alias `Count` = the function's return type (number)# Equivalent shorthand: `:result-def` uses the binding name as alias nametype-def: true (or the bare ` :type-def shorthand) uses the binding’s
own name as the alias name; type-def: "Name" uses an explicit name.
result-def is identical in shape but registers an alias for the function’s
return type rather than the full function type. result-def on a
non-function binding emits a warning and is skipped.
Common type forms in annotations:
| Syntax | Meaning |
|---|---|
number, string, symbol, bool, null, datetime |
primitives |
any |
gradual/unknown — no type errors |
[T] |
list of T |
NonEmpty([T]) |
non-empty list of T |
(A, B) |
tuple |
[A, B, C…] |
prefix-list: fixed A, B then zero+ C (ASCII ... = …); [C…] ≡ [C] |
{{k: T, ..}} |
open record (at least k: T) |
{{k: T, ..r}} |
named row variable (extra fields in r) |
{{..r, ..s}} |
row concatenation (union of r and s) |
{{k: T}} |
closed record |
block |
any block (no known shape) |
Dict(T) |
homogeneous block — all values type T |
"value" |
literal string — subtype of string; c-string escapes for the quotes: c"\"value\"" |
:name |
literal symbol — subtype of symbol |
A -> B |
function |
A | B |
union |
T? |
partial — sugar for T | ExecutionError |
!T (leading !) |
asserted — checker trusts the annotation, does not verify the body (gotcha) |
ExecutionError |
the type of a raised runtime error |
a, b |
type variable (kind *) |
m a |
constructor application (m of kind * -> * applied to a) |
forall a. T |
explicit quantification over kind-* variable |
forall (m :: * -> *) a. T |
explicit quantification with kind annotation |
IO(T) |
IO action producing T |
Lens(a, b) |
lens |
Traversal(a, b) |
traversal |
User-defined monads: monad({ bind(m,f): ..., return(v): ... })
derives the standard combinators (map, then, and-then, join,
sequence, map-m, filter-m) and annotates them with
forall (m :: * -> *) types. The type checker understands them
polymorphically, so passing the wrong type triggers a warning:
my-for: monad({bind(m, f): m mapcat(f), return(v): [v]})[1, 2, 3] my-for.map(true) # warning: expected a → b, found boolImportant: record braces ({) in type strings trigger eucalypt
string interpolation. Always escape with {{ and }}:
"{{name: string, ..}} -> string" not "{name: string, ..} -> string".
Types without braces ("number -> number", "IO(T)") need no escaping.
Literal string types ("value") escape their quotes with c-string escapes:
c"\"value\"". Mind |/-> precedence — bracket a union in argument
position: c"(\"a\" | \"b\") -> bool".
Partial functions: functions that may raise a runtime error use the
T? postfix sugar — equivalent to T | ExecutionError. Several
prelude functions are partial by nature:
nth : number → [a] → a? # out-of-range indexparse-as : symbol → string → any? # invalid input formatlookup : symbol → Dict(a) → a? # key not foundA partial result flowing into any (unannotated code) is silent —
a warning fires only when the receiving position is explicitly annotated
as total:
` { type: "number" }result: [1, 2, 3] nth(0) # warning: expected number, found number?Flow-sensitive narrowing: when a type-predicate test (number?,
string?, bool?, null?, list?, block?, symbol?) on an
annotated variable is used as the condition of if, and, or,
cond, or a structural wrapper (e.g. then(t,f,c): if(c,t,f)), the
checker narrows the variable’s type in each branch. Non-structural
wrappers (e.g. my-if(c,t,_f): t) are not recognised as branchers
and do not trigger narrowing.
LSP alias navigation: alias names written inside type: strings
support go-to-definition, hover (shows the alias name and resolved type), and
rename. This works for plain, unescaped type strings only — escaped or
interpolated strings ("{{...}}") degrade gracefully with no crash. Rename
updates plain-string references; any interpolated references that still mention
the old name will produce an “unknown alias” type warning after the rename.
See Type Checking for the full guide.
1.6 Function Application
Section titled “1.6 Function Application”# Standard call (NO whitespace before paren)f(x, y)
# Catenation / pipeline (single argument, becomes LAST param)x f # = f(x)x f g h # = h(g(f(x)))[1,2,3] map(inc) # map(inc, [1,2,3])
# Partial application (all functions are curried)add(1) # returns a function that adds 1[1,2,3] map(+ 10) # section: adds 10 to each
# Sections (operator with gaps filled by implicit params)(+ 1) # function: _ + 1(* 2) # function: _ * 2(> 3) # function: _ > 3(/) # function: _ / _ (two params)1.7 Lookup and Generalised Lookup
Section titled “1.7 Lookup and Generalised Lookup”# Simple property lookup (dot, precedence 90)block.keyconfig.db.host
# Generalised lookup (evaluate RHS in block scope){ a: 3 b: 4 }.(a + b) # 7{ a: 3 b: 4 }.[a, b] # [3, 4]{ a: 3 b: 4 }."{a} and {b}" # "3 and 4"Warning: . binds very tightly (precedence 90). list head.name
groups head.name into one unit first, and that unit — not list
— is what gets applied: it parses as head.name(list), not
(list head).name. Use parentheses: (list head).name.
1.8 Anaphora (Implicit Parameters)
Section titled “1.8 Anaphora (Implicit Parameters)”| Type | Numbered | Unnumbered | Scope |
|---|---|---|---|
| Expression | _0, _1, _2 |
_ (each _ = new param) |
Expression |
| Block | •0, •1, •2 |
• (each • = new param) |
Block |
| String | {0}, {1}, {2} |
{} (each {} = new param) |
String literal |
# Expression anaphora[1,2,3] map(_0 * _0) # square: [1,4,9][1,2,3] filter(_ > 1) # [2,3]
# Block anaphora (• = bullet, Option-8 on Mac){ x: • y: • } # two-param function returning block[[1,2],[3,4]] map({ x: • y: • } uncurry)
# Pseudo-lambda via block anaphora + generalised lookup{ x: • y: • }.(x + y) # anonymous two-param function
# String anaphora[1,2,3] map("item: {}") # ["item: 1", "item: 2", "item: 3"]"{1},{0}" # two-param function, reversed orderImportant: anaphora cannot be nested. For complex cases, use named functions.
1.9 Imports
Section titled “1.9 Imports”# Unit-level import (available everywhere in file){ import: "lib.eu" }
# Named import (access as namespace){ import: "cfg=config.yaml" }host: cfg.host
# Multiple imports — MUST be in one block, NOT separate blocks{ import: ["helpers.eu", "cfg=config.eu"] }
# WRONG: { import: "a.eu" }# { import: "b.eu" } ← this is a separate block, not a second import
# Format override{ import: "data=yaml@records.txt" }
# Scoped import (on specific declaration)` { import: "math.eu" }calculations: { result: advanced-calc(10) }
# Git import (transitive relative imports inside the fetched file# are also resolved from the same repo/commit, not the local filesystem){ import: { git: "https://github.com/user/lib" commit: "abc123def456" import: "helpers.eu" } }
# Namespaced git import — prefix the repo-relative path with "name="{ import: { git: "https://github.com/user/lib" commit: "abc123def456" import: "x=helpers.eu" } }x.some-function()
# Streaming imports (lazy, for large files){ import: "events=jsonl-stream@events.jsonl" }{ import: "rows=csv-stream@big.csv" }{ import: "lines=text-stream@log.txt" }Import resolution order: relative paths are resolved by searching:
- The directory containing the importing
.eufile (source-relative) - The directories on the lib path (
-Lflags and CWD)
This means a file at lib/utils.eu that imports "helpers/misc.eu" will find
lib/helpers/misc.eu without needing -L lib on the command line. This works
transitively, so lib/helpers/misc.eu can in turn import "sub/detail.eu" and
it will resolve as lib/helpers/sub/detail.eu.
1.10 Quoted Identifiers
Section titled “1.10 Quoted Identifiers”Single quotes turn any character sequence into a normal identifier:
home: { '.bashrc': false 'notes.txt': true}z: home.'notes.txt'2. Operator Precedence Table
Section titled “2. Operator Precedence Table”All values verified against src/core/metadata.rs (named_precedence)
and lib/prelude.eu operator metadata.
From highest (tightest) to lowest binding:
| Prec | Name | Assoc | Operators | Description |
|---|---|---|---|---|
| 95 | – | prefix | ↑ |
Head (tight prefix) |
| 90 | lookup | left | . (built-in) |
Property lookup |
| 90 | lookup | left | ~ |
Safe key lookup (null-propagating) |
| 90 | call | left | (built-in) | Function call |
| 88 | bool-unary | prefix | !, ¬ |
Boolean negation |
| 88 | bool-unary | postfix | ✓ |
Not-null check (true if not null) |
| 88 | – | – | ∘, ; |
Composition (actual prec 88 from prelude) |
| 85 | exp | right | ^ |
Power |
| 85 | exp | – | !! (nth) |
Indexing |
| 80 | prod | left | *, /, ÷, % |
Multiplication, floor division, precise division, floor modulo |
| 75 | sum | left | +, - |
Addition, subtraction |
| 60 | shift | – | (shift ops) | Reserved |
| 55 | bitwise | – | (bitwise ops) | Reserved |
| 50 | cmp | left | <, >, <=, >= |
Comparison |
| 45 | append | left | ++ |
List concatenation |
| 45 | append | left | << |
Deep merge |
| 42 | map | left | <$> |
Functor map |
| 40 | eq | left | =, != |
Equality |
| 40 | eq | left | ∣, ∤ |
Divides, does not divide: 3 ∣ 12 is m % n = 0; ∣ is U+2223, not | |
| 35 | bool-prod | left | &&, ∧ |
Logical AND |
| 30 | bool-sum | left | ||, ∨ |
Logical OR |
| 20 | cat | left | (catenation) | Juxtaposition / pipeline |
| 15 | clause | left | =>, ⇒ |
Cond clause builder (condition => result) |
| 10 | apply | left | @ |
Function application |
| 5 | meta | left | //, //<<, //=, //=>, //=?, //=?>, //! |
Metadata and assertions |
Named precedence levels for use in operator metadata: :lookup,
:call, :bool-unary, :exp, :prod, :sum, :shift, :bitwise,
:cmp, :append, :map, :eq, :bool-prod, :bool-sum, :cat,
:apply, :meta.
User-defined operators default to left-associative, precedence 50
(:cmp level). Set custom values via metadata:
` { associates: :right precedence: :sum }(x +++ y): x + yComposition operators ∘ and ; are defined at precedence 88 in
the prelude (between bool-unary and exp):
f ∘ g— compose right-to-left (gthenf), right-associativef ; g— compose left-to-right (ftheng), left-associative
3. Top 30 Prelude Functions
Section titled “3. Top 30 Prelude Functions”All signatures verified against lib/prelude.eu. Pipeline style shown
where idiomatic (catenated argument is always the last parameter).
3.1 List Functions
Section titled “3.1 List Functions”map(f, l) — transform each element
Section titled “map(f, l) — transform each element”[1, 2, 3] map(inc) # [2, 3, 4][1, 2, 3] map(* 10) # [10, 20, 30]["a","b"] map(str.to-upper) # ["A", "B"]filter(p?, l) — keep elements satisfying predicate
Section titled “filter(p?, l) — keep elements satisfying predicate”[1,2,3,4,5] filter(> 3) # [4, 5][1,2,3,4,5] filter(pos?) # [1, 2, 3, 4, 5]foldl(op, i, l) — left fold
Section titled “foldl(op, i, l) — left fold”foldl(+, 0, [1,2,3,4,5]) # 15[1,2,3] foldl(+, 0) # ERROR: use foldl(+, 0, [1,2,3])Note: foldl takes 3 args. In pipeline: the list is the last arg, so
[1,2,3,4,5] foldl(+, 0) does NOT work — you must call
foldl(+, 0, [1,2,3,4,5]) directly, or partially apply:
sum: foldl(+, 0)[1,2,3,4,5] sum # 15foldr(op, i, l) — right fold
Section titled “foldr(op, i, l) — right fold”foldr(cons, [], [1,2,3]) # [1, 2, 3] (identity)foldr(++, [], [[1,2],[3,4]]) # [1, 2, 3, 4]head(xs) — first element (panics if empty)
Section titled “head(xs) — first element (panics if empty)”[10, 20, 30] head # 10The type checker warns if xs could be empty (List(T) or List(Never)).
Use nil? narrowing or annotate as NonEmpty([T]) to suppress. On a
Tuple([A, B, ...]) literal, head synthesises the precise type A.
tail(xs) — all but first (panics if empty)
Section titled “tail(xs) — all but first (panics if empty)”[10, 20, 30] tail # [20, 30]On a Tuple([A, B, C]), tail synthesises Tuple([B, C]).
cons(h, t) — prepend element to list
Section titled “cons(h, t) — prepend element to list”cons(0, [1, 2, 3]) # [0, 1, 2, 3]cons and ‖ return NonEmpty([a]) — the result is guaranteed non-empty.
reverse(l) — reverse a list
Section titled “reverse(l) — reverse a list”[1, 2, 3] reverse # [3, 2, 1]count(l) — number of elements
Section titled “count(l) — number of elements”[10, 20, 30] count # 3zip(l1, l2) — pair elements from two lists
Section titled “zip(l1, l2) — pair elements from two lists”zip([:a,:b,:c], [1,2,3]) # [[:a,1], [:b,2], [:c,3]]concat(ls) — flatten one level of nesting
Section titled “concat(ls) — flatten one level of nesting”concat([[1,2], [3], [4,5]]) # [1, 2, 3, 4, 5]mapcat(f, l) — map then concatenate (flatMap)
Section titled “mapcat(f, l) — map then concatenate (flatMap)”["ab","cd"] mapcat(str.letters) # ["a","b","c","d"]take(n, l) — first n elements
Section titled “take(n, l) — first n elements”[1,2,3,4,5] take(3) # [1, 2, 3][1,2,3] take(1.5) # error: take count 1.5 must be an integerA non-integer count or index is an error in take, drop, split-at,
rotate, nth, update-nth, window, window-all and the sample
functions. range takes bounds, not a count, and accepts non-integers.
drop(n, l) — remove first n elements
Section titled “drop(n, l) — remove first n elements”[1,2,3,4,5] drop(3) # [4, 5][1,2,3] drop(5) # [] (stops at the end of the list)any(p?, l) — true if any element satisfies p?
Section titled “any(p?, l) — true if any element satisfies p?”[1, 2, 3] any(> 2) # true[1, 2, 3] any(> 5) # falseall(p?, l) — true if all elements satisfy p?
Section titled “all(p?, l) — true if all elements satisfy p?”[2, 4, 6] all(> 0) # true[2, 4, 6] all(> 3) # false3.2 Block Functions
Section titled “3.2 Block Functions”keys(b) — list of keys (as symbols)
Section titled “keys(b) — list of keys (as symbols)”{ a: 1 b: 2 c: 3 } keys # [:a, :b, :c]values(b) — list of values
Section titled “values(b) — list of values”{ a: 1 b: 2 c: 3 } values # [1, 2, 3]elements(b) — list of [key, value] pairs
Section titled “elements(b) — list of [key, value] pairs”{ a: 1 b: 2 } elements # [[:a, 1], [:b, 2]]merge(b1, b2) — shallow merge (b2 overrides b1)
Section titled “merge(b1, b2) — shallow merge (b2 overrides b1)”merge({ a: 1 }, { b: 2 }) # { a: 1 b: 2 }{ a: 1 } { a: 2 } # { a: 2 } (catenation = merge)has(s, b) — does block have key s? (s is a symbol)
Section titled “has(s, b) — does block have key s? (s is a symbol)”{ a: 1 b: 2 } has(:a) # true{ a: 1 b: 2 } has(:z) # falselookup(s, b) — look up key s (panics if missing)
Section titled “lookup(s, b) — look up key s (panics if missing)”{ a: 1 b: 2 } lookup(:b) # 2lookup-or(s, d, b) — look up key s with default d
Section titled “lookup-or(s, d, b) — look up key s with default d”{ a: 1 } lookup-or(:z, 99) # 99{ a: 1 } lookup-or(:a, 99) # 1deep-find(k, b) — find all values for key k at any depth
Section titled “deep-find(k, b) — find all values for key k at any depth”{ a: { x: 1 } b: { x: 2 } } deep-find(:x) # [1, 2]deep-query(pattern, b) — query with dot-separated glob pattern
Section titled “deep-query(pattern, b) — query with dot-separated glob pattern”Patterns: bare foo = **.foo; * = one level; ** = any depth.
{ a: { b: { c: 1 } } } deep-query("a.b.c") # [1]{ a: { x: 1 } b: { x: 2 } } deep-query("*.x") # [1, 2]select(ks, b) — sub-block with only listed keys
Section titled “select(ks, b) — sub-block with only listed keys”{ a: 1 b: 2 c: 3 } select([:a, :c]) # { a: 1 c: 3 }{ a: 1 b: 2 } select([]) # {}{ a: 1 b: 2 } select([:z]) # {}dissoc(ks, b) — sub-block with listed keys removed
Section titled “dissoc(ks, b) — sub-block with listed keys removed”{ a: 1 b: 2 c: 3 } dissoc([:a, :c]) # { b: 2 }{ a: 1 b: 2 } dissoc([]) # { a: 1 b: 2 }{ a: 1 b: 2 } dissoc([:z]) # { a: 1 b: 2 }{ a: 1 } dissoc([:a]) # {}3.2a Sets and Vecs
Section titled “3.2a Sets and Vecs”Build a collection from a list with of; from-list is an alias of it
(the same function), pairing with to-list. Elements must be primitives
(numbers, strings, symbols).
s: [3, 1, 3, 2] set.of # set of 1, 2, 3 (alias: set.from-list)s set.to-list # [1, 2, 3] — sorted, duplicates removed2 ∈ s # truev: [10, 20, 30] vec.of # O(1) indexed access (alias: vec.from-list)v vec.nth(1) # 203.2b Dicts
Section titled “3.2b Dicts”A dict is a persistent dictionary ordered by key, with O(log n) get,
assoc and dissoc. Keys are numbers, strings, symbols, or lists of those
(nested at most 32 deep); 1 and 1.0 are the same key. Values are lazy
and computed at most once, so a dict can refer to itself as a memo table.
Collection argument last, as for sets.
d: [[:b, 2], [:a, 1]] dict.of # alias: dict.from-listd dict.get(:a) # 1 (an error if absent)d dict.get-or(:z, 0) # 0d dict.assoc([3, 4], :pt) # list keys, e.g. coordinatesd dict.dissoc(:b) dict.size # 1d dict.to-list # [[:a, 1], [:b, 2]] — key orderOrdered operations, updates and merges:
d dict.keys # [:a, :b] (dict.values: [1, 2])d dict.min # [:a, 1] (dict.max: [:b, 2])d dict.pop-min # [:a, 1, rest] — rest is d without :ad dict.range(:a, :b) # the sub-dict with :a ≤ k < :bd dict.update(:a, + 1, 0) # :a mapped to 2 (lazily); absent keys start from 0d dict.update-strict(:a, + 1, 0) # the same, evaluated now: use it for countingb dict.merge-with(+, a) # union of a and b, a's value + b's on collisions{x: 1} dict.from-block # dict keyed :x (dict.to-block converts back)A dict keyed by [priority, item] is a priority queue: pop-min takes the
next item, assoc pushes one. Updates and merges store lazy values; in a
counting loop use update-strict or merge-with-strict, which evaluate each
new value, so no chain of unevaluated additions builds up.
Order across types: numbers < strings < symbols (by name) < lists
(lexicographic). dict.of keeps the first of equal keys and the last value.
A dict cannot be rendered yet; render dict.to-list instead.
3.3 String Functions (str namespace)
Section titled “3.3 String Functions (str namespace)”str.split-on(re, s) — split string on regex
Section titled “str.split-on(re, s) — split string on regex”"one-two-three" str.split-on("-") # ["one", "two", "three"]"a.b.c" str.split-on("[.]") # ["a", "b", "c"]str.join-on(sep, l) — join list with separator
Section titled “str.join-on(sep, l) — join list with separator”["a", "b", "c"] str.join-on(", ") # "a, b, c"str.to-upper(s) — convert to upper case
Section titled “str.to-upper(s) — convert to upper case”"hello" str.to-upper # "HELLO"str.to-lower(s) — convert to lower case
Section titled “str.to-lower(s) — convert to lower case”"GOODBYE" str.to-lower # "goodbye"str.matches?(re, s) — does regex match full string?
Section titled “str.matches?(re, s) — does regex match full string?”"hello" str.matches?("^h.*o$") # true"hello" str.matches?("^H") # false3.4 Combinators
Section titled “3.4 Combinators”See also: identity(v), const(k, _), compose(f, g, x),
flip(f, x, y), complement(p?), curry(f, x, y),
uncurry(f, l), cond(l, d).
cond takes a list of clauses built with => / ⇒ (precedence 15)
and a default value. Each clause is condition => result; the first
true clause wins:
classify(n): cond[n < 0 => "negative", n > 100 => "huge", "normal"]Flow-sensitive narrowing applies inside each cond clause when the
condition is a type-predicate test on an annotated variable.
3.5 Type Predicates
Section titled “3.5 Type Predicates”42 number? # true"hi" string? # true:foo symbol? # truetrue bool? # true{} block? # true[] list? # true42 string? # falseAll predicates take one argument and return a boolean. datetime?(v) is also available for zoned-datetime values.
3.5a Type Specs — as-spec
Section titled “3.5a Type Specs — as-spec”Convert a type annotation (an s"…" type-data value) to a match?-compatible pattern:
schema: s"{ name: string, age: number }" as-spec
{name: "Alice", age: 30} match?(schema) # true{name: "Alice", age: "old"} match?(schema) # falseMapping:
| Type form | Pattern produced |
|---|---|
Number, String, Symbol, Bool, Null, DateTime, Any |
Corresponding predicate (number?, string?, …) |
{ k: T } record |
Block pattern {k: T-spec, …} (open matching, extra keys ignored) |
[T] list |
Predicate: list? ∧ all(T-spec) |
A | B union |
Predicate: true if value matches any branch |
T? partial/nullable |
Predicate: null? or T-spec |
(T1, T2, …) tuple |
List pattern [T1-spec, T2-spec, …] (exact length) |
[A, B, C…] prefix-list |
Predicate: list? of length ≥ prefix, each prefix element matches, remainder matches the tail spec |
A → B function |
Predicate: __SATURATED not (checks it is a function) |
forall … |
Erase quantifier, spec the body |
| Type variables | any? (unconstrained at runtime) |
3.5b Structural Contracts — validate and ensure
Section titled “3.5b Structural Contracts — validate and ensure”as-spec/match? answer one bit. For external data at an ingress
boundary, lib/contract.eu gives a located report instead.
{ import: "contract.eu" }
schema: s"{ name: string, port: number, tags?: [string] }"
# A report — a list of blocks. [] means conformant. No SHAPE of data makes# it raise (see the caveat below).report: { name: "web", port: "8080" } validate(schema)# => [{ path: "port", kind: :type-mismatch, expected: "number", found: "string" }]
# Data returned unchanged on success; raises EU-EVAL-CONTRACT otherwise.config: { name: "web", port: 8080 } ensure(schema)Both take the receiver last, so data validate(spec) reads correctly.
kind |
path points at |
expected |
found |
|---|---|---|---|
:type-mismatch |
the value | rendered type | runtime type name |
:missing |
the containing record | the missing key | :absent |
:unexpected |
the record | :closed |
list of surplus keys |
:length |
the list | required length | actual length |
Paths are strings for reading, not eucalypt source: servers[2].port, ""
at the root, 'my key' for a non-identifier key. An indexed path does not
evaluate as written ([2] is a list literal, so servers[2] is
catenation) — navigate with (xs nth(2)).port or a lens.
- A closed spec (
{a: number}) reports surplus keys; an open one ({a: number, ..}or{a: number, ..r}) ignores them — the spec literal means the same thing statically and at runtime. k?: T— absent is conformant, present must match.- Only the paths the spec names are forced. Key enumeration (and so
closedness detection) never forces a value;
any,topand type variables force nothing at all. A spec is safe to apply to a value with diverging subtrees it does not name. - The raise caveat: no shape of data makes
validateraise, but it propagates a raise from forcing a value the spec names — total with respect to shape, not to evaluation. - A malformed spec raises
panic("validate: not a type spec")— a different error from a contract violation, so a schema typo cannot masquerade as bad data. - Literal types (
"prod",:ok) are checked by equality here but not byas-spec, which matches anything for them (eu-pub3r).
See Structural Contracts.
3.6 Command-line Argument Parsing
Section titled “3.6 Command-line Argument Parsing”parse-args(defaults, args) — structured CLI argument parsing
Section titled “parse-args(defaults, args) — structured CLI argument parsing”Parse args (a list of strings, typically io.args) against defaults:
` :suppressdefaults: { ` { short: :v doc: "Verbose" flag: true } verbose: false ` { short: :o doc: "Output file" } output: "out.yaml" ` { doc: "Repeat count" } count: 1}
main: io.args parse-args(defaults)Returns defaults block with parsed values overridden, plus args key for positional arguments.
Metadata keys: short (symbol, short flag), doc (string, help text), flag (bool, toggle).
Supported forms: --key value, --key=value, --flag, -x, -xy (combined shorts), positionals, --help.
See docs/reference/prelude/io.md for full documentation.
4. Pipeline Patterns and Idioms
Section titled “4. Pipeline Patterns and Idioms”4.1 Basic Pipeline
Section titled “4.1 Basic Pipeline”Read left to right: data flows through transformations.
[1, 2, 3, 4, 5] filter(> 2) map(* 10) reverse# Result: [50, 40, 30]4.2 Pipeline with Named Stages
Section titled “4.2 Pipeline with Named Stages”Use :suppress to hide intermediate data values from output. Note: :suppress is only needed on data declarations that would otherwise appear in rendered output. Functions do not need :suppress — they are not rendered.
` :suppressraw-data: [ { name: "alice" score: 85 } { name: "bob" score: 92 } { name: "charlie" score: 78 }]
result: raw-data filter(_.score >= 90) map(_.name) map(str.to-upper)4.3 Conditional Pipeline
Section titled “4.3 Conditional Pipeline”Use then(true-val, false-val) at the end of a pipeline:
[1, 2, 3] count (> 2) then("many", "few") # "many"Or use when(p?, f, x) to conditionally transform:
5 when(> 3, * 10) # 50 (condition met, apply * 10)2 when(> 3, * 10) # 2 (condition not met, pass through)4.4 Configuration Layering with Deep Merge
Section titled “4.4 Configuration Layering with Deep Merge”base: { server: { host: "0.0.0.0" port: 8080 workers: 4 } logging: { level: "info" format: "json" }}
production: base << { server: { workers: 16 } logging: { level: "warn" }}
development: base << { server: { host: "localhost" } logging: { level: "debug" format: "text" }}4.5 Building Blocks from Lists
Section titled “4.5 Building Blocks from Lists”# Zip keys and values into a blockzip-kv([:x, :y, :z], [1, 2, 3])# Result: { x: 1 y: 2 z: 3 }
# Reconstruct from element pairs[[:a, 1], [:b, 2]] block# Result: { a: 1 b: 2 }
# Merge a list of blocks[{a: 1}, {b: 2}, {c: 3}] merge-all# Result: { a: 1 b: 2 c: 3 }4.6 Transforming Block Values
Section titled “4.6 Transforming Block Values”# Apply function to all values{ a: 1 b: 2 c: 3 } map-values(* 10)# Result: { a: 10 b: 20 c: 30 }
# Transform keys{ a: 1 b: 2 } map-keys(sym ∘ str.prefix("x-") ∘ str.of)# Result: { x-a: 1 x-b: 2 }4.7 Nested Block Modification
Section titled “4.7 Nested Block Modification”config: { server: { db: { port: 5432 } } }
# Set a nested valueconfig alter([:server, :db, :port], 3306)
# Apply a function to a nested valueconfig update([:server, :db, :port], inc)
# Shallow merge into a nested block (replaces nested blocks)config merge-at([:server, :db], { host: "10.0.0.1" })
# Deep merge into a nested block (preserves nested blocks)config deep-merge-at([:server, :db], { host: "10.0.0.1" })4.8 Grouping and Sorting
Section titled “4.8 Grouping and Sorting”# Sort numbers[5, 3, 1, 4, 2] qsort(<) # [1, 2, 3, 4, 5][30, 10, 20] sort-nums # [10, 20, 30]
# Sort by extracted keypeople sort-by-num(_.age)
# Group by key functionitems group-by(_.category)4.9 Composition
Section titled “4.9 Composition”# Right-to-left composition (g then f)shout: str.to-upper ∘ str.suffix("!")"hello" shout # "HELLO!"
# Left-to-right composition (f then g)process: filter(> 0) ; map(* 2)[-1, 2, -3, 4] process # [4, 8]4.10 Handling Data from External Sources
Section titled “4.10 Handling Data from External Sources”# CSV (values are always strings, use num to convert){ import: "rows=transactions.csv" }total: rows map(_.amount num) foldl(+, 0)
# Command-line argumentsname: io.args head-or("World")greeting: "Hello, {name}!"
# Environment variableshome: io.env lookup-or(:HOME, "/tmp")4.11 Infinite Lists
Section titled “4.11 Infinite Lists”# Infinite repetitionrepeat(:x) take(4) # [:x, :x, :x, :x]
# Infinite sequence of integersints-from(1) take(5) # [1, 2, 3, 4, 5]
# Range (finite)range(1, 6) # [1, 2, 3, 4, 5]range(6, 1) # [] (empty when e <= b)
# Infinite iterationiterate(* 2, 1) take(6) # [1, 2, 4, 8, 16, 32]5. Common Pitfalls
Section titled “5. Common Pitfalls”5.1 Catenation Applies the LAST Argument
Section titled “5.1 Catenation Applies the LAST Argument”When using pipeline style, the catenated value becomes the last
parameter. [1,2,3] map(inc) means map(inc, [1,2,3]) because the
list is the last argument.
For foldl(op, init, list), you cannot write
[1,2,3] foldl(+, 0) — you need either foldl(+, 0, [1,2,3]) or
define a partial: sum: foldl(+, 0) then [1,2,3] sum.
5.2 Dot Binds Tighter Than Catenation
Section titled “5.2 Dot Binds Tighter Than Catenation”. has precedence 90 vs catenation at 20. So:
list head.name # WRONG: parses as head.name(list)(list head).name # RIGHT: get head, then lookup .nameThe ↑ prefix operator (precedence 95) binds even tighter: ↑xs.name
= (↑xs).name.
5.3 No Whitespace in Call Syntax
Section titled “5.3 No Whitespace in Call Syntax”Whether (, [, or { immediately follows the callee (no space) is
what distinguishes a call from catenation:
f(x) # function callf (x) # catenation: applies f to (x) as pipelinef[1,2] # juxtaposed call with list argumentf [1,2] # catenation: applies f to [1,2] as pipelinef{a: 1} # juxtaposed call with block argumentf {a: 1}# catenation: applies f to {a: 1} as pipeline5.4 map vs mapcat
Section titled “5.4 map vs mapcat”map(f, l)— appliesfto each element, preserving list structuremapcat(f, l)— appliesf(which must return a list) and concatenates all results
["ab","cd"] map(str.letters) # [["a","b"], ["c","d"]]["ab","cd"] mapcat(str.letters) # ["a", "b", "c", "d"]5.5 Simple Lookup vs Generalised Lookup
Section titled “5.5 Simple Lookup vs Generalised Lookup”Simple lookup (.name): Key lookup restricted to the block’s
own bindings. Outer scope is never consulted.
{ x: 1 }.x # => 1 (key found){ x: 1 }.y # => key error (even if y exists in outer scope)Generalised lookup (.{ block }, .(expr), ."string",
.[list]): RHS evaluated in the block’s scope. Block bindings
shadow outer scope; names not in the block fall through to outer
scope.
y: 5{ x: 1 }.(x + y) # => 6 (x from block, y from outer){ x: 1 }.{ sum: x + y } # => { sum: 6 }Runtime lookup: lookup(:key, block) / block lookup(:key) —
dynamic key lookup using a symbol value. Use when the key is
computed or stored in a variable.
Monadic blocks in lookup position use implicit return and see the LHS bindings:
{ x: 1 }.{ :let y: x + 10 }.y # => 115.6 merge vs deep-merge (<<)
Section titled “5.6 merge vs deep-merge (<<)”merge(a, b)— shallow merge; nested blocks inbcompletely replace those inadeep-merge(a, b)/a << b— recursively merges nested blocks, but lists are still replaced entirely
5.7 has Takes a Symbol, Not a String
Section titled “5.7 has Takes a Symbol, Not a String”{ a: 1 } has(:a) # true{ a: 1 } has("a") # WRONG: "a" is a string, not symbol :aUse sym("a") to convert a string to a symbol if needed.
5.8 deep-find Takes a Symbol, Not a String
Section titled “5.8 deep-find Takes a Symbol, Not a String”{ a: { x: 1 } } deep-find(:x) # [1] — correct{ a: { x: 1 } } deep-find("x") # WRONG — takes a symboldeep-find, deep-find-first, and deep-find-paths take a symbol key,
matching the rest of the prelude (has(:key), lookup-or(:key, ...)).
5.9 Self-Reference Creates Infinite Recursion
Section titled “5.9 Self-Reference Creates Infinite Recursion”name: "foo"x: { name: name } # INFINITE RECURSION: inner name refers to itselfThe inner name shadows the outer one. Use a different name or
generalised lookup.
5.10 Anaphora Scope Limits
Section titled “5.10 Anaphora Scope Limits”- Expression anaphora (
_,_0) do not cross commas, catenation boundaries, or function argument lists - Block anaphora (
•,•0) are scoped to the enclosing block - String anaphora (
{},{0}) are scoped to the enclosing string - None of the anaphora types can be nested
5.11 Functions That Do NOT Exist
Section titled “5.11 Functions That Do NOT Exist”The following are commonly assumed but are not in the prelude:
flatten— useconcat(flattens one level)unique— does not exist in preludeeven?/odd?— do not exist (use2 ∣ x/2 ∤ x, orx % 2 = 0;∣is U+2223 divides, not|)round/ceil— usefloorandceiling(or bracket notation⌊n⌋and⌈n⌉)select(ks, b)— exists:{ a: 1, b: 2, c: 3 } select([:a, :c])→{ a: 1, c: 3 }dissoc(ks, b)— exists:{ a: 1, b: 2 } dissoc([:a])→{ b: 2 }
These do exist and are commonly available:
str.trim(s)— trims leading/trailing whitespacestr.replace(pattern, replacement, s)— replaces all regex matchesstr.contains?(pattern, s)— true ifscontains a match for regexpatternstr.starts-with?(re, s)— true ifsstarts with regex matchstr.ends-with?(re, s)— true ifsends with regex matchabs(n)— absolute valuestr.to-upper(s)/str.to-lower(s)— case conversion (notstr.upper/str.lower)
5.12 str.split-on Uses Regex, Not Literal Strings
Section titled “5.12 str.split-on Uses Regex, Not Literal Strings”"a.b.c" str.split-on(".") # WRONG: "." matches any char"a.b.c" str.split-on("[.]") # RIGHT: escaped dot in regexAll str.match, str.split, str.matches? functions use regex
patterns.
5.13 if With Anaphora Does Not Create a Rule Function
Section titled “5.13 if With Anaphora Does Not Create a Rule Function”# WRONG: _ creates an anaphoric function, if evaluates it as a booleandata deep-transform(if(_ symbol?, :replaced, null))
# RIGHT: use a named function as the rulereplace-syms(v): if(v symbol?, :replaced, null)data deep-transform(replace-syms)if evaluates its first argument as a condition. _ symbol? in
that position creates a function, not a boolean. Use a named
function or when instead.
5.14 keys Returns Symbols
Section titled “5.14 keys Returns Symbols”Block keys are symbols. keys returns a list of symbols — do NOT
map(sym) over them:
{a: 1, b: 2} keys # [:a, :b] — already symbols{a: 1, b: 2} keys map(sym) # WRONG: sym expects a string5.15 Use deep-transform for Recursive Rewrites
Section titled “5.15 Use deep-transform for Recursive Rewrites”deep-transform(rule, data) applies rule at each node. Return a
value to replace, or null to recurse into children. Eliminates
hand-rolled recursive if(block?, ..., if(list?, ...)) dispatch:
# Replace all symbols matching a setrename(v): if(v ∈ ks, prefix(v), null)data deep-transform(rename)5.16 Use map-elements and bimap for Block Transforms
Section titled “5.16 Use map-elements and bimap for Block Transforms”map-elements(f, blk) applies f to each [key, value] pair and
rebuilds the block. Combine with bimap for point-free transforms:
blk map-elements(bimap(rename-key, transform-value))5.17 {x: x} Is Always Self-Reference
Section titled “5.17 {x: x} Is Always Self-Reference”Every declaration inside a block literal sees itself — including its
own right-hand side. {x: x} does not copy an outer x into the
block; it creates a self-referential binding that refers to itself.
This most often bites function parameters:
# WRONG — cmd refers to itself (infinite loop), not the parametershell-spec(cmd): { :io-shell cmd: cmd, timeout: 30 }
# CORRECT — use a different name so the parameter isn't shadowedshell-spec(c): { :io-shell cmd: c, timeout: 30 }To transform a value and keep its name use a :let block (see 5.18)
or pick a different local name.
5.18 Sequential Bindings: Use :let Blocks
Section titled “5.18 Sequential Bindings: Use :let Blocks”Eucalypt has no let … in syntax. For sequential, non-self-referential
bindings, use a :let block:
# WRONG — 'in' is unresolved; 'let' is just a prelude valueresult: let x: 1 in x + 2
# CORRECT — :let block; y can safely reference xresult: { :let x: 1 y: x + 2 }.y:let RHS expressions see the outer scope (including prior :let
bindings), not themselves. This is the one place where {name: name}
is not self-reference — the RHS is evaluated before the new binding
takes effect:
# Transform xs and keep its name — RHS xs is the function parameternormalise(xs): { :let xs: xs map(clean) }.xs5.19 Backtick and Braces in Doc Strings
Section titled “5.19 Backtick and Braces in Doc Strings”The backtick (`) inside a string is not an escape — it is
parsed as a metadata marker. Using ` inside a doc string causes
a parse error:
# WRONG — backtick inside string triggers metadata parsing` "Run via `sh -c`"my-fn(x): x
# CORRECT — use plain prose, no backticks inside the string` "Run via sh -c"my-fn(x): xSimilarly, { inside a doc string starts string interpolation. A
literal { example (e.g. "e.g. {stdin: s}") will try to look up
stdin as a variable and likely fail:
# WRONG — {stdin: s} triggers interpolation; s becomes a free variable` "Provide options e.g. {stdin: s}"run(opts): opts
# CORRECT — describe with plain prose` "Provide options e.g. a block with stdin field"run(opts): opts5.20 :suppress Leaks Through References
Section titled “5.20 :suppress Leaks Through References”` :suppress hides a binding from rendered output, but the flag
travels with the value. If you reference a suppressed value, the
field it lands in is also silently suppressed:
# WRONG — log4j is suppressed, so @id silently disappears` :suppresslog4j: "pkg:maven/log4j-core@2.17.1"
entry: { '@id': log4j } # renders as {} — @id is gone
# CORRECT — suppress the container, reference members directly` :suppresspurls: { log4j: "pkg:maven/log4j-core@2.17.1" }
entry: { '@id': purls.log4j } # @id is present and correctOnly suppress a binding you do not reference elsewhere. To hide values you do reference, group them in a suppressed block and look up members from it.
5.21 Cons Pattern Only Valid in Function Parameters
Section titled “5.21 Cons Pattern Only Valid in Function Parameters”The [h : t] destructuring pattern is only valid in a function
parameter position. A colon inside a list expression is a parse
error:
# VALID — cons pattern in function parameterfirst([h : t]): h
# INVALID — colon is not a list separator in expressionsbad: [1 : rest] # parse errorIn expressions, use the ‖ cons operator or cons prelude function:
built: 1 ‖ [2, 3] # => [1, 2, 3]also: cons(1, [2, 3]) # => [1, 2, 3]5.22 Prefer when Over if for Conditional Transforms
Section titled “5.22 Prefer when Over if for Conditional Transforms”when(pred?, f, x) applies f when the predicate is satisfied and
passes x through unchanged. It is cleaner than if(pred?(x), f(x), x) because it avoids repeating x:
# Prefer — no repetitionx when(number?, + 1)
# Avoid — x appears three timesif(x number?, x + 1, x)5.23 Anaphor Scoping: Parentheses Are Opaque
Section titled “5.23 Anaphor Scoping: Parentheses Are Opaque”Parentheses create a new anaphor scope. Anaphors inside parens form a lambda at the paren level, not at the enclosing expression:
(_0 + _1) / 2 # WRONG: (_0 + _1) is its own 2-arg lambda; # / 2 then tries to divide a function by 2
# Correct: use a named helperavg2(a, b): (a + b) / 2Subsumption: if the enclosing expression already has a direct anaphor, inner paren groups become transparent — their anaphors join the outer scope:
# _0✓ makes the outer expression anaphoric, so _0 inside count(_0)# is subsumed — both refer to the same parameter_0✓ && count(_0) >= 4 # λ(a). a != null && count(a) >= 4Without the outer _0✓, the _0 inside count(_0) would form a
separate lambda at the ArgTuple level.
6. Quick CLI Reference
Section titled “6. Quick CLI Reference”eu file.eu # Evaluate, output YAMLeu -j file.eu # Output JSONeu -x toml file.eu # Output TOMLeu -x text file.eu # Output plain texteu -e 'expression' # Evaluate inline expressioneu data.yaml transform.eu # Merge inputs (left to right)eu name=data.json app.eu # Named inputeu -t target file.eu # Render specific targeteu list-targets file.eu # List available targetseu test file.eu # Run embedded testseu fmt file.eu # Format sourceeu fmt --write file.eu # Format in placeeu -o output.json file.eu # Write to file (format inferred)eu -Q file.eu # Suppress preludeeu --seed 42 file.eu # Deterministic randomeu -e 'io.args' -- arg1 arg2 # Pass arguments7. Complete str Namespace Reference
Section titled “7. Complete str Namespace Reference”All functions verified against lib/prelude.eu:
| Function | Signature | Description |
|---|---|---|
str.of |
of(e) |
Convert any value to string |
str.split |
split(s, re) |
Split string s on regex re |
str.split-on |
split-on(re, s) |
Split s on regex re (pipeline-friendly) |
str.join |
join(l, sep) |
Join list l with separator sep |
str.join-on |
join-on(sep, l) |
Join l with sep (pipeline-friendly) |
str.match |
match(s, re) |
Match s against regex, return [full, groups…] |
str.match-with |
match-with(re, s) |
Match s against re (pipeline-friendly) |
str.extract |
extract(re, s) |
Extract first capture group or error |
str.extract-or |
extract-or(re, d, s) |
Extract first capture group or default d |
str.matches |
matches(s, re) |
All matches of re in s |
str.matches-of |
matches-of(re, s) |
All matches (pipeline-friendly) |
str.matches? |
matches?(re, s) |
True if re matches full string s |
str.letters |
letters(s) |
List of individual characters |
str.len |
len(s) |
String length in characters |
str.fmt |
fmt(x, spec) |
Printf-style format |
str.to-upper |
to-upper(s) |
Convert to upper case |
str.to-lower |
to-lower(s) |
Convert to lower case |
str.prefix |
prefix(b, a) |
Prepend b onto a |
str.suffix |
suffix(b, a) |
Append b onto a |
str.base64-encode |
base64-encode(s) |
Base64 encode |
str.base64-decode |
base64-decode(s) |
Base64 decode |
str.sha256 |
sha256(s) |
SHA-256 hash (lowercase hex) |
8. Assertion and Test Operators
Section titled “8. Assertion and Test Operators”All at precedence 5 (:meta).
Expectations (return boolean; panic in normal mode, return false in test mode):
| Operator | Description |
|---|---|
e //= v |
Expect e equals v; returns true on success |
e //=? f |
Expect f(e) is true; returns true on success |
e //! |
Expect e is true; returns true on success |
Assertions (return e; panic in normal mode, return false in test mode):
| Operator | Description |
|---|---|
e //=> v |
Assert e equals v; returns e on success |
e //=?> f |
Assert f(e) is true; returns e on success |
Assertions are useful in pipelines — they validate a value and pass it through:
data //=?> non-nil? map(process) //=?> (count > 0)All expectation and assertion operators use the same unified
__EXPECT BIF. On failure, they emit a diagnostic showing the
expected and actual values.
Metadata operators:
| Operator | Description |
|---|---|
e // m |
Attach metadata block m to value e |
e //<< m |
Merge m into existing metadata of e |
Debug intrinsics (low-level BIFs for diagnostics and test infrastructure):
| BIF | Signature | Description |
|---|---|---|
__DBG_REPR(v) |
unk → str |
Render any eucalypt value as a compact human-readable string (e.g. 42, "hello", :foo, true, null, [], {block}) |
__EXPECT(actual, repr, pass, ret) |
unk × str × bool × unk → unk |
Unified expectation/assertion: returns ret on success; on failure emits diagnostic and panics (normal) or returns false (test mode) |
__DBG(label, v) |
str × unk → unk |
Print debug output to stderr; return v transparently |
9. Debug Tracing
Section titled “9. Debug Tracing”Operators and functions for inspecting values at runtime.
| Form | Description |
|---|---|
▶ v |
Print v to stderr and return it transparently. Prefix operator, precedence 85. |
v dbg{} |
Print v to stderr and return it transparently. |
v dbg{label: "x"} |
Print x: <repr> to stderr and return v transparently. |
Output format: ▶ <repr> or ▶ label: <repr>.
▶ is intentionally prominent — the Unicode triangle is hard to overlook
in a code review.
10. Version Requirements
Section titled “10. Version Requirements”Declare a minimum eucalypt version at the top of any .eu file that depends
on features introduced in a specific release.
_ : eu.requires(">=0.8")eu.requires takes a semver constraint string. It returns null on success
and raises VersionRequirementFailed on failure. Because eu.requires
returns null it must be assigned to _ (a discard binding) — a bare
expression at the top level cannot reference eu directly.
Constraint syntax
Section titled “Constraint syntax”Uses semver constraint syntax:
| Constraint | Meaning |
|---|---|
">=0.8" |
Version 0.8.0 or later |
"^0.8" |
Compatible with 0.8 (i.e. 0.8.x) |
">=0.8, <1.0" |
0.8.x up to but not including 1.0 |
Convention
Section titled “Convention”- Every shipped library file (
lib/lens.eu,lib/state.eu,lib/markup.eu) uses_ : eu.requires(">=0.8")near the top. - Place the declaration after any unit-level metadata block or file-level doc string, before the first binding definition.
- Build metadata (
+N) is ignored by the version check —">=0.8"matches0.8.0+1685.
11. Lens Library (lib/lens.eu)
Section titled “11. Lens Library (lib/lens.eu)”The lens library provides composable, bidirectional accessors for nested data. Import it with:
{ import: "lens.eu" }What a Lens Is
Section titled “What a Lens Is”A lens is a reusable description of a position within a data
structure. Once defined, the same lens can read the value at that
position (view), replace it (over with ->const), or transform
it with a function (over) — always returning the complete, updated
structure.
A traversal extends this to multiple positions: over applies a
function at each focus and rebuilds the whole structure; to-list-of
collects all foci into a list.
Core Operations
Section titled “Core Operations”| Function | Signature | Description |
|---|---|---|
view(lens, data) |
Lens(a, b) → a → b |
Read the focused value |
over(optic, fn, data) |
(Lens(a,b) | Traversal(a,b)) → (b→b) → a → a |
Transform at each focus |
to-list-of(optic, data) |
(Lens(a,b) | Traversal(a,b)) → a → [b] |
Collect all foci into a list |
parts-of(traversal) |
Traversal(a,b) → Lens(a,[b]) |
Turn a traversal into a lens on the list of all foci |
Setting a value: use over with the -> const operator to
replace rather than transform:
data over(lens, -> "new-value") # -> discards the old valueLens and Traversal Constructors
Section titled “Lens and Traversal Constructors”| Constructor | Type | Description |
|---|---|---|
at(key) |
symbol → Lens({..}, a) |
Focus on block value at symbol key |
ix(n) |
number → Lens([a], a) |
Focus on list element at index n |
item(pred) |
(a→bool) → Lens([a], a) |
Focus on first list element matching predicate |
element(pred) |
((sym,any)→bool) → Lens({..},[sym,any]) |
Focus on first [key,value] pair matching predicate |
_value |
Lens([a], a) |
Focus on value (index 1) of a [key,value] pair |
_key |
Lens([a], a) |
Focus on key (index 0) of a [key,value] pair |
each |
Traversal([a], a) |
Traverse all list elements |
filtered(pred) |
(a→bool) → Traversal([a], a) |
Traverse only matching list elements |
each-element |
Traversal({..}, [sym,any]) |
Traverse all block kv pairs |
filtered-elements(pred) |
((sym,any)→bool) → Traversal({..}, [sym,any]) |
Traverse matching block kv pairs |
Composition
Section titled “Composition”Compose with ∘ (right-to-left) to focus deeper. A lens composed
with a traversal yields a traversal:
# Equivalent compositionsat(:server) ∘ at(:db) ∘ at(:host)‹:server :db :host› # shorthand bracket form
# Mix key and index navigation‹:items 0 :meta :title› # at(:items) ∘ ix(0) ∘ at(:meta) ∘ at(:title)The ‹› bracket shorthand converts symbols to at lenses and
numbers to ix lenses, then composes them with ∘. Lens function
values may also appear in the path: ‹element(by-key(_ = :b)) _value›.
Examples
Section titled “Examples”{ import: "lens.eu" }
config: { server: { db: { host: "localhost", port: 5432 } } }
# Read with viewhost: config view(‹:server :db :host›)# => "localhost"
# Update with over — whole config returned, rest unchangedupdated: config over(‹:server :db :host›, -> "10.0.0.5")# => { server: { db: { host: "10.0.0.5", port: 5432 } } }
# Apply a function to a nested valuebumped: config over(‹:server :db :port›, + 1)# => { server: { db: { host: "localhost", port: 5433 } } }Traversal example — transform a field across every list element:
{ import: "lens.eu" }
records: [{name: "a", score: 10}, {name: "b", score: 20}]
# Collect all scoresrecords to-list-of(each ∘ at(:score)) # => [10, 20]
# Double all scoresrecords over(each ∘ at(:score), * 2)# => [{name: "a", score: 20}, {name: "b", score: 40}]
# Sort all scores as a group (parts-of)[3, 1, 4, 1, 5] over(parts-of(each), sort-nums) # => [1, 1, 3, 4, 5]Type Checker Integration
Section titled “Type Checker Integration”The type checker understands Lens(a, b) and Traversal(a, b) as
opaque types. Using view on a traversal (instead of to-list-of)
triggers a type warning. Composing incompatible optics (e.g.
Lens(a, b) ∘ Lens(c, d) where b ≠ c) also produces a warning.
See Navigating Nested Data for
a complete tutorial including ~ safe navigation and match?.