Skip to content
eucalypt
v0.15.0

Syntax Cheat Sheet

A dense single-page reference covering all syntax forms, operators, common patterns, and key prelude functions.

Type Syntax Examples
Integer digits 42, -7, 0
Float digits with . 3.14, -0.5
String double quotes "hello", "line\nbreak"
Symbol colon prefix :key, :name
Boolean literals true, false
Null literal null
ZDT t"..." prefix t"2024-03-15", t"2024-03-15T14:30:00Z"
# Property declaration
name: expression
# Function declaration
f(x, y): expression
# Operator declaration (binary)
(l ++ r): expression
# Operator declaration (prefix / postfix)
(! x): expression
(x ******): expression
# Block literal
{ a: 1 b: 2 c: 3 }
# Commas are optional
{ a: 1, b: 2, c: 3 }
# Nested blocks
{ outer: { inner: "value" } }

Top-level unit: the file itself is an implicit block (no braces needed).

# List literal
[1, 2, 3]
# Empty list
[]
# Mixed types
[1, "two", :three, true]
# Insert expressions with {braces}
"Hello, {name}!"
# String anaphora (defines a function)
"#{}" # one-parameter function
"{0} and {1}" # two-parameter function
# Line comment (to end of line)
x: 42 # inline comment
Form Syntax Notes
Property name: expr Defines a named value
Function f(x, y): expr Named function with parameters
Block pattern f({x y}): expr Destructures block argument fields
Block rename f({x: a y: b}): expr Destructures with renamed bindings
List pattern f([a, b, c]): expr Destructures fixed-length list
Cons pattern f([h : t]): expr Destructures head and tail of list
Binary operator (l op r): expr Infix operator
Prefix operator (op x): expr Unary prefix
Postfix operator (x op): expr Unary postfix
Idiot bracket ⟦ xs ⟧: expr Custom Unicode bracket pair
# Suppress from output (still visible to importers)
` :suppress
secret: 42
# Internal — invisible to importers AND output (unit-private)
` :internal
private-data: "unit only"
# Structured form
` { export: :internal }
also-private: "hidden"

Idiot brackets allow custom Unicode bracket pairs that collect their content items into a list and pass it to a function.

# Declare a bracket pair function (xs receives a list)
⟦ xs ⟧: xs map(_ * 2)
# Items are collected as a list: ⟦ a b c ⟧ = ⟦⟧([a, b, c])
result: ⟦ 3 4 5 ⟧ # [6, 8, 10]

Any matching Unicode bracket pair works, e.g. ⟦⟧, ⟨⟩, ⟪⟫, ⌈⌉, ⌊⌋, ‹›, ⦃⦄, ⦇⦈, ⦉⦊, «», 【】, 〔〕, 〖〗, 〘〙, 〚〛.

The prelude defines ⌈⌉ and ⌊⌋ for ceiling and floor:

⌈3.2⌉ # 4
⌊3.8⌋ # 3
⌈-1.5⌉ # -1
⌊-1.5⌋ # -2

Monadic sequencing (like do-notation) is supported via bracket pairs or block metadata. A bracket block or annotated block followed by .expr desugars to a bind chain.

# Bracket pair definition — explicit functions
⟦{}⟧: { :monad bind: my-bind return: my-return }
# Bracket pair definition — namespace reference
⟦{}⟧: { :monad namespace: my-monad }
# ⟦ a: ma b: mb ⟧.return_expr
# desugars to: bind(ma, (a): bind(mb, (b): return(return_expr)))
result: ⟦ a: ma b: mb ⟧.(a + b)

All declarations are bind steps whose names are in scope for later declarations and the return expression. The return expression follows the closing bracket (or block) as .name, .(expr), or .[list].

Restrictions: monad brackets cannot be empty (at least one declaration required) and cannot contain block metadata.

Built-in monadic namespaces:

Tag Monad Action type Element type
:io IO effects IO(a) a
:random Random state stream → {value: a, rest: stream} a
:state Block state (import state.eu) state → {value: a, state: state} a
:let Identity (sequential bindings) any same
:for List (comprehensions) [a] a
# List comprehension: cartesian product with filter
{ :for x: [1, 2, 3], _: [x] filter(> 1) }.(x * 10)
# => [20, 30]
# Declaration metadata (backtick prefix)
` "Documentation string"
name: value
# Structured metadata
` { doc: "description" associates: :left precedence: 50 }
(l op r): expr
# Unit-level metadata (first expression in file)
{ :doc "Unit description" }
a: 1

Special metadata keys: :target, :suppress, :internal, :main, associates, precedence, import, :deprecated.

Declaration visibility (export:): :normal (default, rendered and importable), :suppress (hidden from output, still importable), :internal (hidden from output AND importers — unit-private).

Mark a declaration as deprecated to emit a warning whenever it is used:

# Bare deprecation (simplest form)
` :deprecated
old-fn(x): x
# With a message
` { deprecated: "use new-fn instead" }
old-fn(x): x
# With message and replacement hint
` { deprecated: "use new-fn instead"
replaced-by: "new-fn" }
old-fn(x): x

Deprecation warnings appear on stderr during evaluation and in LSP diagnostics. Under eu check --strict, deprecation warnings become errors.

A declaration nested inside a namespace block is matched by the dotted path a caller writes, not by its bare name — deprecating exec inside state warns on state.exec and leaves both io.exec and any unrelated top-level exec alone. A reference only counts if it resolves to the declaration: a lambda parameter or a local block that merely shares the namespace’s name never inherits its deprecation. The one case that does still match by name is a top-level block of your own sharing a deprecated library namespace’s name.

# Parenthesised application (no whitespace before paren)
f(x, y)
# Catenation (pipeline style, single argument)
x f # equivalent to f(x)
x f g h # equivalent to h(g(f(x)))
# Partial application (curried)
add(1) # returns a function adding 1
# Sections (operator with gaps)
(+ 1) # function: add 1
(* 2) # function: multiply by 2
(/) # function: floor divide (two params)
(÷) # function: precise divide (two params)
# Simple lookup
block.key
# Generalised lookup (evaluate RHS in block's 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"
Type Numbered Unnumbered Scope
Expression _0, _1, _2 _ (each use = new param) Expression
Block •0, •1, •2 • (each use = new param) Block
String {0}, {1}, {2} {} (each use = new param) String
# Expression anaphora
map(_0 * _0) # square each element
map(_ + 1) # increment (each _ is a new param)
# Block anaphora (bullet = Option-8 on Mac)
{ x: •0 y: •1 } # two-parameter block function
# String anaphora
map("item: {}") # format each element

From highest to lowest binding:

Prec Name Assoc Operators Description
95 – prefix ↑ Tight prefix (head)
90 lookup left . Field access / lookup
90 lookup left ~ Safe key lookup (null-propagating)
88 bool-unary prefix !, ¬ Boolean negation
88 bool-unary postfix ✓ Not-null check (true if not null)
88 – right/left ∘, ; Composition (right-to-left, left-to-right)
85 exp right ^ Power
85 exp right !! Indexing (xs !! 0, arrays use list: a !! [r,c])
80 prod left *, /, ÷, % Multiplication, floor division, precise division, floor modulo
75 sum left +, - Addition, subtraction
55 – right ‖ List cons (prepend element)
50 cmp left <, >, <=, >= Comparison
45 append right ++, << List append, 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 right =>, ⇒ Cond clause builder (condition => result)
10 apply right @ Function application
5 meta right //, //<<, //=, //=>, //=?, //=?>, //! Metadata / assertions

User-defined operators default to left-associative, precedence 50. Set custom values via metadata: ` { precedence: 75 associates: :right }

Named precedence levels for use in metadata: lookup, call, bool-unary, exp, prod, sum, shift, bitwise, cmp, append, map, eq, bool-prod, bool-sum, cat, apply, meta.

# Catenation of blocks performs a shallow merge
{ a: 1 } { b: 2 } # { a: 1 b: 2 }
{ a: 1 } { a: 2 } # { a: 2 }
# Deep merge operator
{ a: { x: 1 } } << { a: { y: 2 } } # { a: { x: 1 y: 2 } }
# Unit-level import
{ import: "lib.eu" }
# Named import
{ import: "cfg=config.eu" }
# Multiple imports
{ import: ["dep-a.eu", "dep-b.eu"] }
# Format override
{ import: "yaml@data.txt" }
# Git import
{ import: { git: "https://..." commit: "sha..." import: "file.eu" } }
Function Description
head First element
tail All but first
cons(x, xs) Prepend element
map(f) Transform each element
filter(p?) Keep elements matching predicate
foldl(f, init) Left fold
foldr(f, init) Right fold
sort-by(f) Sort by key function
take(n) First n elements ([] if n <= 0)
drop(n) Remove first n (list unchanged if n <= 0; [] if n exceeds the length)
nth(n) Element at index n from 0 (error if out of range)
zip Pair elements from two lists
zip-with(f) Combine elements with function
concat Flatten nested lists one level (use concat, not flatten — does not exist)
reverse Reverse a list
count Number of elements
range(a, b) Integers from a to b-1 ([] if b <= a)
nil? Is the list empty?
any(p?) Does any element match?
all(p?) Do all elements match?
nub-by(f) Deduplicate by key function (no unique in prelude)

A non-integer count or index is an error in take, drop, split-at, rotate, nth, update-nth, window, window-all and the sample functions; an integral float such as 2.0 is accepted.

Function Description
lookup(key) Look up a key (symbol)
lookup-or(key, default) Look up with default
has(key) Does block contain key?
keys List of keys (as symbols)
values List of values
elements List of {key, value} pairs
map-keys(f) Transform keys
map-values(f) Transform values
filter-items(p?) Keep entries matching predicate (use with by-key, by-value)
merge(b) Shallow merge
deep-merge(b) Deep recursive merge
sort-keys Sort by key name
Function Description
str.len(s) String length
str.to-upper(s) Upper case
str.to-lower(s) Lower case
str.starts-with?(re, s) Starts with regex match?
str.ends-with?(re, s) Ends with regex match?
str.contains?(re, s) Contains regex match?
str.matches?(re, s) Matches full regex?
str.split-on(re, s) Split by regex (pipeline-friendly)
str.join-on(sep, l) Join list with separator (pipeline-friendly)
str.replace(re, rep, s) Replace all regex matches
str.prefix(b, a) Prepend b onto a
str.suffix(b, a) Append b onto a

All str regex functions treat the pattern argument as a regular expression. str.split-on and str.contains? are pipeline-friendly (data is last arg). Note: str.trim does not exist — strip leading/trailing manually with str.replace.

Function Description
render(value) Serialise to YAML string
render-as(fmt, value) Serialise to string in named format
parse-as(fmt, str) Parse string as structured data (inverse of render-as)

Formats for render-as: :yaml, :json, :toml, :text, :edn, :html. Formats for parse-as: :json, :yaml, :toml, :csv, :xml, :edn, :jsonl.

parse-as is safe for untrusted input — YAML !eu tags are never evaluated.

Function Description
identity Returns its argument unchanged
const(k) Always returns k
compose(f, g) or f ∘ g Compose functions
flip(f) Swap argument order
complement(p?) Negate a predicate
curry(f) Curry a function taking a pair
uncurry(f) Uncurry to take a pair
Function Description
num Parse string to number
abs Absolute value
negate Negate number
inc / dec Increment / decrement
max(a, b) / min(a, b) Maximum / minimum
zero? / pos? / neg? Sign predicates
floor / ceiling / ⌊n⌋ / ⌈n⌉ Rounding (no round)
even? / odd? Do not exist — use 2 ∣ x / 2 ∤ x (U+2223 divides, not |) or x % 2 = 0

Import with { import: "lens.eu" }. A lens focuses on a single position in a structure; a traversal focuses on multiple positions.

Core operations:

Operation Description
view(lens, data) Read the focused value
over(optic, fn, data) Apply fn at each focus; return whole structure
to-list-of(optic, data) Collect all foci into a list
parts-of(traversal) Turn traversal into a lens on the list of all foci

Set a value with over and the -> const operator: data over(lens, -> newval).

Constructors:

Constructor Description
at(key) Block value at symbol key
ix(n) List element at index n
item(p?) First list element matching predicate
element(p?) First block [key, value] pair matching predicate
_value Value (index 1) of a [key, value] pair
_key Key (index 0) of a [key, value] pair
each All list elements (traversal)
filtered(p?) Matching list elements (traversal)
each-element All block kv pairs (traversal)
filtered-elements(p?) Matching block kv pairs (traversal)

Composition: ∘ composes right-to-left; ‹› is bracket shorthand.

{ import: "lens.eu" }
config: { server: { db: { host: "localhost", port: 5432 } } }
# Bracket shorthand — symbols become at(), numbers become ix()
config view(‹:server :db :host›) # "localhost"
config over(‹:server :db :port›, + 1) # whole config with port 5433
# Traversal — operate across all list elements
records: [{name: "a", score: 10}, {name: "b", score: 20}]
records to-list-of(each ∘ at(:score)) # [10, 20]
records over(each ∘ at(:score), * 2) # scores doubled
[3, 1, 2] over(parts-of(each), sort-nums) # [1, 2, 3]

Persistent dictionaries ordered by key. Keys are numbers, strings, symbols or lists of those (e.g. [x, y] coordinates); values are arbitrary and lazy, and each is computed at most once.

Expression Description
pairs dict.of / pairs dict.from-list Dict from [key, value] pairs (aliases); equal keys keep the first key and the last value
dict.empty / d dict.empty? The empty dict / has no entries?
d dict.get(k) Value at k; an error if absent
d dict.get-or(k, default) Value at k, or default
d dict.assoc(k, v) / d dict.dissoc(k) New dict with k set / removed (O(log n))
d dict.contains?(k) / d dict.size Holds k? / number of entries
d dict.to-list [key, value] pairs in key order
d dict.keys / d dict.values Keys / values in key order
d dict.min / d dict.max [key, value] for the least / greatest key; an error if empty
d dict.pop-min / d dict.pop-max [key, value, rest]; with keys [priority, item], a priority queue
d dict.range(lo, hi) Sub-dict of keys lo ≤ k < hi
d dict.update(k, f, default) Map k to f(old), old defaulting to default (lazy)
d dict.update-strict(k, f, default) As update, evaluating f(old) now: d dict.update-strict(k, + 1, 0) counts
b dict.merge-with(f, a) Union; f(va, vb) where both hold a key (lazy; merge-with-strict evaluates it)
b dict.from-block / d dict.to-block Block to dict (symbol keys) / dict to block (string, symbol and number keys)

Keys order numbers < strings < symbols < lists; 1 and 1.0 are the same key. A dict cannot be rendered yet: convert it with dict.to-list first.

Function Description
arr.zeros(shape) Create array of zeros; shape is a list of integers
arr.fill(shape, val) Create array filled with val
arr.from-flat(shape, vals) Create array from flat list of numbers
a arr.get(coords) Element at coordinate list coords
a arr.set(coords, val) New array with element at coords set to val
arr.shape(a) Shape as list of integers
arr.rank(a) Number of dimensions
arr.length(a) Total number of elements
arr.to-list(a) Flat list of elements in row-major order
arr.array?(x) / is-array?(x) Is x an array?
arr.transpose(a) Reverse all axes
a arr.reshape(shape) Reshape (total elements must match)
a arr.slice(axis, idx) Slice along axis at idx (reduces rank by 1)
arr.add(a, b) / arr.sub / arr.mul / arr.div Element-wise arithmetic; b may be scalar
a !! coords Index operator; for arrays, coords is a list e.g. [row, col]
arr.indices(a) List of coordinate lists for every element (row-major)
arr.map(f, a) Apply f to each element; same shape
arr.map-indexed(f, a) Apply f(coords, val) to each element; same shape
arr.fold(f, init, a) Left-fold over all elements in row-major order
a arr.neighbours(coords, offsets) Values at valid in-bounds neighbours given offset vectors

The standard +, -, *, / operators are polymorphic and apply element-wise when either operand is an array. Scalar broadcasting is supported.

Expression Description
xs set.of / xs set.from-list Set of primitives from a list (one pass; the names are aliases)
s set.to-list Sorted list of a set’s elements
v ∈ s / v ∉ s Membership
∅ The empty set
xs vec.of / xs vec.from-list Vec of primitives with O(1) indexed access (aliases)
v vec.nth(n) / vec.len(v) Element at index n (0-based; a negative or non-integer n is an error) / length
Binding / Function Description
io.env Block of environment variables
io.epoch-time Unix timestamp at launch
io.args Command-line arguments (after --)
io.random Infinite lazy stream of random floats
io.RANDOM_SEED Current random seed
io.return(a) Wrap a pure value in the IO monad
io.bind(action, cont) Sequence two IO actions
io.shell(cmd) Run cmd via sh -c; returns {stdout, stderr, exit-code}
io.shell-with(opts, cmd) Run cmd with extra options (e.g. {stdin: s, timeout: 60}). Pipeline: "cmd" shell-with(opts)
io.exec([cmd : args]) Run cmd directly (no shell); argument is a list [cmd, arg1, arg2, ...]
io.exec-with(opts, [cmd : args]) Run cmd directly with extra options. Pipeline: ["git", "log"] exec-with(opts)
io.check(result) Fail with stderr if exit-code is non-zero; otherwise return result
io.map(f, action) Apply pure function to result of IO action (fmap)

Test expectations (panic in normal mode, return false in test mode):

Operator Description
e //= v Expect e equals v, return true/false
e //=? f Expect f(e) is true, return true/false
e //! Expect e is true, return true/false

Assertions (return e, panic on failure in normal mode):

Operator Description
e //=> v Assert e equals v, return e
e //=?> f Assert f(e) is true, return e
Terminal window
eu file.eu # Evaluate file, output YAML
eu -j file.eu # Output JSON
eu -x text file.eu # Output plain text
eu -e 'expression' # Evaluate expression
eu a.yaml b.eu # Merge inputs
eu -t target file.eu # Render specific target
eu list-targets file.eu # List targets
eu --seed 42 file.eu # Deterministic random
eu -Q file.eu # Suppress prelude
eu fmt file.eu # Format source
eu dump stg file.eu # Dump STG syntax
eu -- arg1 arg2 # Pass arguments (io.args)
eu check file.eu # Type-check only, report warnings
eu check --strict file.eu # Treat type warnings as errors
eu file.eu --strict # Evaluate, abort first if type warnings
eu file.eu --suppress-type-warnings # Evaluate, silence warnings
eu doc file.eu # Extract documentation (Markdown)
eu doc --format json file.eu # Extract as JSON Schema
eu doc --check file.eu # Report documentation coverage

Type annotations live in declaration metadata alongside doc strings. All annotations are optional — unannotated code is treated as any.

` { doc: "`double(x)` - double a number."
type: "number -> number" }
double(x): x * 2
# Operator
` { doc: "..."
type: "a -> (a -> b) -> b"
associates: :left
precedence: 20 }
(x |> f): f(x)
# In unit metadata
{ types: { Person: "{name: string, age: number, ..}" } }
# Via type-def: on a canonical instance
` { type-def: "Point" }
origin: { x: 0, y: 0 }
Syntax Meaning
number number
string string
symbol symbol
bool boolean
null null
datetime zoned date-time
any gradual/unknown — no type errors
[T] homogeneous list of T
NonEmpty([T]) non-empty list of T
(A, B) 2-tuple; (A, B, C) for triple
(A,) 1-tuple
[A, B, C…] prefix-list: fixed A, B then zero+ C (... = …)
{k: T} closed record
{k: T, ..} open record (at least k: T)
{k: T, ..r} named row variable (in string: {{k: T, ..r}})
{..r, ..s} row concatenation (in string: {{..r, ..s}})
block any block (no known shape)
Dict(T) homogeneous block — all values type T
Name (capitalised) type alias — defined via types: { Name: "..." }
"value" literal string type (subtype of string); c-string escapes for the quotes: c"\"value\""
:name literal symbol type (subtype of symbol)
T? partial — sugar for T | ExecutionError; marks functions that may raise an error
!T (leading !) asserted — checker trusts the annotation without verifying the body (gotcha)
ExecutionError the type of a raised runtime error
A -> B function
A | B union
a, b, s type variable, kind * (lowercase)
m a constructor application (m :: * -> * applied to a)
forall a. T explicit quantification (kind-*)
forall (m :: * -> *) a. T explicit quantification with kind annotation
IO(T) IO action producing T
Lens(a, b) lens focusing on b within a
Traversal(a, b) traversal over b’s within a
set ordered set of primitives
vec flat vector of primitives
array n-dimensional number array

monad({ bind(m,f): ..., return(v): ... }) derives the standard combinators (map, then, and-then, join, sequence, map-m, filter-m) annotated with forall (m :: * -> *) types. The type checker understands them polymorphically — passing a non-function to my-monad.map triggers a warning.