Epsil for AI Agents
A condensed reference for language models and coding agents writing Epsil.
Every code fence on this page is executed by the test suite and its // ➔
output verified — the examples cannot drift from the implementation. Epsil is
experimental: syntax and semantics may change between releases.
This card names the epsil command for each task: running a program, checking
it, looking up the library. When you have no shell, use what your host gives
you for the same task. The Epsil MCP server has the tools evaluate, check
and doc; a host that embeds Epsil can give its own tools; on the web, the
Standard Library page lists every function.
What Epsil Is
Epsil is a programming language for scientific computing built on the Compute
Engine. It is symbolic and exact by default: 1/3 is the rational one
third, not 0.333…, and ln(2) or sqrt(2) stay symbolic. Ask for a decimal
explicitly with N(expr). A program is a sequence of statements (separated by
newlines or ;); its result is the value of the last statement, so
produce the value you want as the final statement. print(…) writes to the
host console (the evaluate MCP tool returns those lines as output), and
evaluates to nothing. Runtime
problems (a const reassignment, a type mismatch) become ordinary
Error(...) values, not thrown exceptions; malformed source produces
diagnostics with source locations.
Run it: npx epsil file.epsil, npx epsil --eval 'expr', stdin, or a REPL
(npx epsil). Diagnostics go to stderr; exit code 0 = success, 1 = error.
Validate without evaluating: npx epsil check file.epsil --json emits
structured diagnostics (positions, fix-its). Look up the library:
npx epsil doc Mean, or search by concept — npx epsil doc "standard deviation". Add --diagnostics json to a run for machine-readable runtime
diagnostics. Embed via executeEpsil(ce, source) from
@cortex-js/compute-engine/epsil. See CLI.
Naming convention: library operators are written in lowercase (sin,
map, simplify, pi) and also answer to their MathJSON names (Sin,
Map, Simplify, Pi). Your variables and functions are lowercase too and
shadow a library name by scope (let sum = 0 makes sum a variable).
Operators with their own syntax have no lowercase spelling (Add is +,
If is if, List is […]). Calling an unknown function is not an
error — the call stays symbolic (a warning diagnostic with a did-you-mean
suggestion fires when a close library name exists, e.g. len → length).
Core Syntax
let x = 5 // mutable declaration
const tau = 6.28 // immutable; reassigning yields an Error value
x = x + 3 // assignment: a bare `=` assigns only as a STATEMENT
f(x) = x^2 // function definition, math style
let square = x => x^2 // anonymous function ("=>" is the lambda arrow)
cube : (x: number) -> number = x^3 // a named function-type annotation binds x
function g(n) { // function definition, block style
let t = n + 1 // blocks are lexically scoped
t * 2 // a block's value is its last expression
}
hold h(e) = head(e) // hold: arguments arrive UNEVALUATED (h(x + 1) ➔ Add)
hold mySum(body, bind i, n) = sum(body, (i, 1, n)) // bind: a bound-variable slot; mySum(k^2, k, 3) ➔ 14
function op(a, b) commutative associative -> number { a + b } // algebraic words in the specifier slot
/// A doc comment right before a definition is its description (About, hover)
let parity = "even" if x % 2 == 0 else "odd" // conditional expression; if is also an expression: if c { a } else { b }
g(x) + f(2)
// ➔ 22
- Comments:
// lineand/* block */. NOT#(that starts a pragma). - Statements: one per line, or separated by
;. Two expressions on one line with no separator is a diagnostic. A line ending in an infix operator continues onto the next line, and so does a line that starts with.(a chain broken before its dots:b.grow(2)then.grow(3)). - Whitespace rule: an infix operator has spaces on both sides or neither
(
a + bora+b;a +bis a diagnostic). Prefix-x/!xand postfixn!must touch their operand. - Types (optional) use the Compute Engine type language:
let n: integer = 4,f(x: real) -> real = x^2. Parameter types are enforced at call time. - Collections: list
[1, 2, 3], setset(1, 2, 3), tuple(1, 2), dictionary{one -> 1, two -> 2}, empty dictionary{}({1, 2, 3}is an error: writeset(1, 2, 3)). Access dictionaries withd["key"]; identifier-shaped keys also have the shorthandd.key. Tuples index like lists (p[1]is the first component); a matrix (list of lists) indexes asm[2, 1]orm[2][1]. - Spread: in a call argument list,
...tsplices a tuple's elements in as positional arguments (f(...p),max(...t),g(1, ...p, ...q)). Tuples only — spreading a list is anincompatible-typeerror — and...is valid nowhere else. - Destructuring:
let (q, r) = divmod(17, 5)binds a tuple's components (constmakes them constants;_skips a position; patterns nest). Tuples only, ≥ 2 elements, initializer required; a shape mismatch is an Error value. For conditional destructuring usematch. The same pattern assigns to EXISTING bindings with:=, evaluating the right side once before it writes anything, so(a, b) := (b, a)swaps. It must be:=— a statement-leading(a, b) = …is a comparison, and is diagnosed. - Block in expression position:
do { … }(a bare{ … }in expression position is always a set/dictionary literal). - LaTeX islands:
$\frac{1}{2}$splices parsed LaTeX into the expression (available in the CLI and any host that injects a LaTeX parser).
Operator precedence, loosest → tightest: := · => · ?? (coalesce) ·
|> (pipe) · -> (key-value) · a if c else b (conditional) · || · && ·
comparisons
== != < <= > >= === in !in is (chainable: 1 < 2 < 3) · .. (range) ·
+ - · * / % · unary - ! · ^/** (right-associative) · postfix !.
Calls f(x) and indexing xs[i] bind tightest of all. A bare = has no
fixed tier: it binds like := when it assigns and like == when it compares.
If You Know Python or JavaScript
Epsil deliberately diverges from these reflexes. Wrong-by-instinct → what actually happens → write instead:
| Reflex | What happens in Epsil | Write instead |
|---|---|---|
xs[0] for first element | Silently yields NaN — indexing is 1-based | xs[1]; negative indices work: xs[-1] is the last element |
7 // 2 floor division | Silent wrong value: // starts a comment, so this is just 7 | floor(7 / 2) |
7 / 2 integer division | Exact rational 7/2, not 3 or 3.5 | floor(7 / 2) for 3; N(7 / 2) for 3.5 |
range(1, 5) excludes end | Inert call + did-you-mean; Range(1, 5) includes 5: [1,2,3,4,5] | 1..n for 1…n inclusive (empty when n < 1) |
x = 5 at top level | Assigns — = assigns only as a whole statement with a name on the left | x == 5 for the equation |
# comment | Diagnostic (# introduces pragmas) | // comment or /* … */ |
def f(x): / (x) => … / lambda x: … | Parse diagnostics; (x) -> … is recovered with a did-you-mean-=> fixit | f(x) = expr, x => expr, or function f(x) { … } |
cond ? a : b | Parse diagnostic | a if cond else b, or if cond { a } else { b } — both are expressions |
elif | Parse diagnostic | else if |
return | Reserved word, not implemented | A block's value is its last expression |
break / continue | Work as expected inside a while/for body; the loop context resets at every function and lambda boundary | (nothing to change) |
print(x) | Inert unknown call; nothing prints | The program's value is its last statement |
len(xs) | Inert + did-you-mean | length(xs) |
s[0] / len(s) on a string | Works — a string is a collection of its characters (grapheme clusters), 1-based | s[1], length(s) |
"a" + "b" | Error values inside an Add | "\(a) and \(b)" interpolation, or join(a, b) |
xs[2] = 9 | Works, as a rebinding: xs = replaceAt(xs, 2, 9). Collections are immutable values, so another name that holds the old list keeps it | (nothing to change) |
A buffer written in place (bytearray, a NumPy array) | A list is rebuilt at each element write | An array: let a = arrayFrom(repeat(0, n), "integer<0..255>"), then a[i] = v stores in place, and every name that holds a sees it. Not a collection: sum(listFrom(a)) (Arrays) |
and / or / not | Parse diagnostics (reserved words) | &&, ||, ! |
x**0.5 habits: x^1/2 | Parses as (x^1)/2 — precedence, not a root | sqrt(x) or x^(1/2) |
math.floor, np.mean | No modules/namespaces | Everything is global: floor, mean, sin, … |
for loop building a value | Loops are for effect; their value is nothing | Accumulate into a let, or use map/filter/reduce |
| f-strings / template literals | Backtick is the verbatim-symbol quote; ${} invalid | "x is \(x)" works in any string |
Comfortable habits that do transfer: ** is an accepted alias of ^
(both right-associative, 2^3^2 → 512); % is Mod with the sign
convention of Python (-7 % 3 → 2); xs[-1] is the last element; 0.1 + 0.2 == 0.3 is True (decimal arithmetic); chained comparisons 1 < 2 < 3
work; 2 in [1, 2, 3] works; lowercase true/false are accepted
(canonically True/False).
Order of Preference
Prefer a library function, then broadcasting, then a pipeline, and write a loop
last. Search the library (epsil doc <keywords>, or your host's lookup) before
you write a loop: nthPrime, primeFactors, gcd, mandelbrot and julia are library
functions, and a hand-written loop for one of them is longer and slower.
- A library function:
gcd(1071, 462),nthPrime(100),count(xs, pred),sum,mean,max. - Broadcasting: arithmetic (
+ - * / ^), the ordering comparisons (< <= > >=) and a function whose parameters are numbers (sqrt,sin,abs,floor,Mod,isPrime,nthPrime, …) apply to each element of a list or a range, and give a list. An aggregate (sum,max,length,gcd) takes the whole list. When you are not sure that a function broadcasts, evaluate it on a short list. - A pipeline:
map(f, xs)andfilter(xs, pred)(note the argument order of each),count,fold,reduce, chained with|>. A pipe stage that is a one-parameter lambda whose body uses its parameter as a number is applied to each element of a list or a range, so it needs nomap:xs |> x => x^2andxs |> _^2arexs^2. In an operator-written stage (_^2,_ + 1)_is the parameter of that lambda; in a call stage (take(_, 10),length(_))_is the whole piped value. - A loop, for an effect (a
print, a write to an array) or for a state whose next value depends on the previous one and whose number of turns is not known in advance.
(sqrt([1, 4, 9]) + 1, (1..5)^2, isPrime(1..6), Mod(1..6, 3) == 0)
// ➔ ([2,3,4], [1,4,9,16,25], [false,true,true,false,true,false], [false,false,true,false,false,true])
(1..5 |> _^2 |> sum, [[1, 2], [3]] |> length(_))
// ➔ (55, 2)
Instead of this loop, which sums the first 100 primes:
let total = 0
let found = 0
let n = 2
while found < 100 {
if isPrime(n) {
total = total + n
found = found + 1
}
n = n + 1
}
total
// ➔ 24133
write the library function, broadcast over a range:
nthPrime(1..100) |> sum
// ➔ 24133
More pairs:
| Instead of a loop that… | Write |
|---|---|
| builds the list of the squares of 1…10 | (1..10)^2 |
adds 1/k for k from 1 to 10 | sum(1 / (1..10)) |
counts the primes p ≤ 100 with p % 4 == 1 | count(1..100, p => isPrime(p) && Mod(p, 4) == 1) |
| keeps the multiples of 3 up to 20 | filter(1..20, k => Mod(k, 3) == 0) |
(sum(1 / (1..10)), count(1..100, p => isPrime(p) && Mod(p, 4) == 1))
// ➔ (7381/2520, 11)
Verified Idioms
The Style Guide states each idiom with its reason; this section is the short form.
Exactness and numeric approximation:
let exact = 1/3 + 1/6 // stays the exact rational 1/2
let sym = sqrt(2) * sqrt(2) // symbolic radicals reduce exactly
"\(exact), \(sym), \(N(pi, 10))"
// ➔ "1/2, 2, 3.141592654"
Functions, recursion (self-reference works in a one-step definition, with
any number of recursive calls — fib(n-1) + fib(n-2) is fine), and closures:
fact(n) = 1 if n <= 1 else n * fact(n - 1)
makeAdder(k) = x => x + k // closures capture lexically
let add10 = makeAdder(10)
add10(fact(5))
// ➔ 130
Collections pipeline — map/filter/reduce for value-producing iteration,
|> to chain; 1..n is an inclusive range:
1..10 |> filter(_, k => k % 2 == 0) |> map(k => k^2, _)
// ➔ [4, 16, 36, 64, 100]
reduce([1, 2, 3, 4], (acc, x) => acc + x, 0) + sum(1..100)
// ➔ 5060
A loop is the right form when each turn depends on the previous one and the
number of turns is not known in advance. It evaluates to nothing, so
accumulate into a variable declared outside. To build a list in a loop, spread
the old list into a new literal (each literal snapshots the current value);
never join(xs, [k]) on every turn, which nests a lazy recipe per turn and
takes seconds by a thousand elements. The Collatz path of 6:
let n = 6
let path = [n]
while n != 1 {
n = n / 2 if n % 2 == 0 else 3 * n + 1
path = [...path, n]
}
path
// ➔ [6, 3, 10, 5, 16, 8, 4, 2, 1]
Structural match (an expression; _ is the wildcard; a bare name binds
— use == expr to compare against a value):
classify(n) = match n {
0 => "zero"
k if k > 0 => "positive"
_ => "negative"
}
classify(-5)
// ➔ "negative"
Symbolic computation:
let poly = simplify(2 + 3x^3 + 2x^2 + x^3 + 1)
let roots = solve(x^2 + x - 6 == 0, x)
let deriv = D(x^3 + x, x)
let area = integrate(sin(x), (x, 0, pi))
(poly, roots, deriv, area)
// ➔ (4x^3 + 2x^2 + 3, [2,-3], 3x^2 + 1, 2)
Lists, slices, and common operators (all indexing is 1-based):
let xs = [10, 20, 30, 40]
(xs[1..2], first(xs), last(xs), sort([3, 1, 2]), indexOf(xs, 30))
// ➔ ([10,20], 10, 40, [1,2,3], 3)
Dictionaries (string keys; dot access is shorthand for identifier-shaped keys):
let d: dictionary<number> = {one -> 1, two -> 2}
(d.two, d["two"], isMissing(d.missing), Coalesce(d.missing, 0))
// ➔ (2, 2, true, 0)
An absent numeric field evaluates to NaN; an absent nonnumeric field remains
missing. isMissing recognizes both forms.
Library Quick Roster
Verified operator names, so you don't have to guess. The complete index, by
category with signatures, is the Standard Library page;
search by concept with epsil doc <keywords>.
- Numbers:
abs,floor,ceil(notCeiling),round,sqrt,max,min(each takes a list or varargs),Mod,gcd,lcm,isPrime,random(a..b). - Lists:
length,first,last,rest,take,drop,reverse,sort(optional comparator — see below),indexOf,join,append,sum,mean,standardDeviation(sample, n−1),map,filter,count(xs)/count(xs, v)/count(xs, pred),reduce(list, f, init),a..binclusive and counting up,Range(a, b, step). - Strings:
characters,stringSplit(s)(splits on whitespace by default),String(x),join(a, b)to concatenate strings,StringJoin(xs, sep?)to join ONE collection with an optional separator (a string subject means its characters, sostringJoin("ab", "cd")is"acdb", not"abcd"— usejoinor"\(a)\(b)"to concatenate). Substring search israngeOf(s, needle)(a span, ormissing),containsSequence,startsWith,endsWith—c in sis character membership. AlsoStringReplace(s, target, replacement, count?),trim/trimStart/trimEnd,stringRepeat,padStart/padEnd,toUpperCase/toLowerCase/caseFold,stringCompare(a, b)(-1/0/1, code-point order) andNumberFrom(s, base?).s[i]is a character; every string operation, and a dictionary lookupd[c], accepts a character as the one-character string (toUpperCase(s[1]), noString(c)needed). - Dictionaries:
keys,values. - Absence:
missingpreserves a missing position;nothingis the value of an empty block, kept as an element like any other value;isMissing,Coalesce. - Symbolic:
simplify,HoldValues(body)(evaluatebodywith its assigned symbols kept symbolic),solve(eq == v, x),D(expr, x),derivative(f),integrate,N,type,isError(x)(true for an error value, or an expression carrying one).
Caution: head and tail exist but are structural operators
(head([1,2,3]) is the operator name "List", not the first element) —
for elements use first/rest.
sort([3, 1, 4, 1, 5], (a, b) => a > b)
// ➔ [5,4,3,1,1]
Watch Out For
- Comparisons have no tolerance:
==,<,<=,>,>=and!=compare two numbers exactly, at the working precision, so1e-11 > 1e-12istrueandsqrt(3.5) * sqrt(3.5) == 3.5isfalse. Compare two computed values withabs(a - b) < eps, or remove a small part withchop. a..bcounts up,Range(a, b)counts towardb:1..nis empty whennis 0, sofor k in 1..n { … }then runs zero times. The callRange(1, n)with no step is[1, 0]whennis 0. To count down, write the step:Range(5, 1, -1).- Laziness:
Range,map,filter,take,drop,joinare generators — they enumerate when materialized (indexed, aggregated, or iterated), and a deferred mapping function reads variables at materialization time. Collection literals snapshot their element values immediately ((take(xs, 3), 1)holds the list of the three elements), and so does an assignment:let ys = filter(xs, p)andxs = filter(xs, p)store the list of the elements when the generator is finite and reads a variable. A generator with no last element (filter(1..oo, p)) stays lazy when it is assigned: a variable operand gives its value at the assignment, and the inline function reads its variables when an element is computed. List a finite part withlistFromto keep the elements of that time. The value of a program (its last statement) is listed too when it is a finite generator:map(u => u + 1, [5, 6])gives the list[6, 7], in the text, the MathJSON and the LaTeX of the value. A range stays a range. - Output is the engine's textual form, with Epsil symbols: a string
prints in quotes (
"florb"), a boolean astrue/false, the absence markers asnothing/missing, and a symbol unquoted (a1). A value that is still a lazy collection (aRange, a generator with no last element) preview-elides above 10 elements ([1,2,3,4,5,...,26,27,28,29,30],[2,4,6,8,10,...]); the value is complete — the CLI's--jsonoutput materializes the full elements (up to 10,000). Literals print in full, and so does a finitemap/filterresult that is the value of the program, because that value is a list. - Arguments are evaluated before a call —
f(a + 1)receives the value — except for aholdfunction (hold f(e) = …), which receives the expression as written and evaluates it wherever the body reads it (call-by-name:hold twice(e) = e + eevaluatesetwice;let v = eonce). Every parameter of a hold function is held; there is no per-parameter form. - Binder variables stay symbolic:
D(expr, x)andintegrate(expr, x)treatxsymbolically even ifxhas an assigned value; the result then evaluates with the value. Solet x = 2followed byN(D(x^3 + x, x))is13— the derivative is taken first. - A variable that holds a formula is read by
D,integrateandseries:let G = sin(x); D(G, x)iscos(x), andlet G = sin(x); integrate(G, x)is-cos(x). Thexin the value is the variable ofD. A sum or a product does not read it: its index does not reach into the value of another variable. - Interpolating a collection broadcasts:
"\(expr)"with a list-valuedexprmaps the string over the elements, yielding a list of strings ("n = \([1, 2])"→["n = 1", "n = 2"]), not one string containing the list. Interpolate scalars only. - Only the last statement's value is returned. An error value in an
earlier statement also emits a
runtime-errordiagnostic so it can't vanish silently. - Boolean inference is sticky: using a bare undeclared symbol as a
boolean operand (
&&/||/!) types itbooleanfor the engine's lifetime; a later numeric use of the same symbol errors. 3!^2is a diagnostic — the lexer reads!^as one operator token. Space it:3! ^ 2.matchbinds bare names:match x { Pi => … }does not compare with π — it binds a new variable namedpi. Pin values with==:match x { == Pi => … }.- The dot calls protocol functions only:
c.area()isarea(c)whenareais aprotocolfunction the type ofcconforms to. A library function is not reached that way —xs.Sort()is the errordot-call-not-a-protocol-function; writesort(xs)orxs |> sort.
For the full reference start at Epsil, the complete grammar in Syntax, and ~70 more verified programs in Examples.