Skip to main content

Evaluation

A whole program is prepared before any statement executes. Types and protocols come first, then function definitions with their paired signature declarations, then all remaining statements in source order. Statements are evaluated sequentially in that canonical order, and the program's value is the last statement's value:

let x = 5
x = x + 3
x
// ➔ 8

No scope is pushed around the whole program: declarations persist across statements, and across cells in a notebook or inputs in a REPL that share one session. Blocks and function bodies still push their own lexical scopes (see Control Flow). A later program may redeclare a session name and establish a new type; assignment keeps the existing binding's contract. See Declarations.

Symbolic by default​

Values stay exact unless you ask otherwise. A transcendental of an exact argument stays symbolic —

ln(2)

evaluates to the symbolic ln(2) (the MathJSON ["Ln", 2]), not a decimal approximation.

Numeric approximation is explicit, via N(expr) — it is a function call, not a language mode:

N(ln(2))

evaluates to 0.6931471805599453….

Values and bindings​

Epsil keeps apart two things many languages blur together:

  • A value — a number, a string, a list, a dictionary, a function — is immutable. Once it exists, nothing anywhere can change it.
  • A binding — the association between a name and a value — is the part that changes. let introduces a binding you may reassign; const one you may not. See Declarations.

Everything below follows from those two sentences. Two kinds of values are the exception, made to change in place: an object (a value of an object{…} type) and an array (see Arrays).

There is no in-place modification. An assignment to an element, xs[2] = 9, does not change the list: it builds a new list and rebinds the name, as xs = replaceAt(xs, 2, 9) does. Another name that holds the old list keeps it:

let xs = [1, 2, 3]
let ys = xs
xs[2] = 9
[xs, ys]
// ➔ [[1, 9, 3], [1, 2, 3]]

So the target must be a name that the program can assign: with const xs = [1, 2, 3], xs[2] = 9 is the error constant-assignment. An element of a nested list has the same form, m[2][1] = 9 or m[2, 1] = 9, which rebinds m.

A write that cannot give a list is an error, and the name keeps its value. A position past the end, zero or not an integer is the error out-of-range (xs[5] = 9 when xs has three elements); the length of a string is its number of characters. A target with no value is the error assignment-to-list-element, and a target that is a number is the error incompatible-type that replaceAt gives. A string and a tuple are written as replaceAt writes them, and give a list: with s = "abc", s[1] = "z" gives the list of characters ["z", "b", "c"]. A string position (xs["a"] = 9) is the error assignment-to-list-element, reported before the program runs, because replaceAt takes only an integer position. A position that is a name with no value (xs[k] = 9 with k unknown) leaves the write unevaluated, and xs holds it.

Operators never modify what you hand them — append, sort, join, map, filter all return a new collection:

let xs = [3, 1, 2]
let ys = sort(xs)
(xs, ys)
// ➔ ([3, 1, 2], [1, 2, 3])

Reassigning one name never disturbs another. Two names holding the same value are independent, because there is no way to reach a value through a name and alter it:

let a = [1, 2, 3]
let b = a
a = [9, 9, 9]
b
// ➔ [1, 2, 3]

This is what makes a value safe to pass around: no function you call, and no name you assign to, can change a collection out from under you. There are no references, no aliasing and no object identity — two collections are the same when they have the same contents, and that is all == ever asks:

[1, 2, 3] == [1, 2, 3]
// ➔ true

A parameter is a binding of its own. A function may reassign its parameter; the caller's binding is untouched:

function reset(v) {
v = 0
v
}
let n = 7
let r = reset(n)
(n, r)
// ➔ (7, 0)

A closure captures the binding, not a snapshot of its value. This is the one place where the distinction is directly visible. A function that refers to an outer name reads that name's current value each time it runs:

let x = 1
f() = x
x = 2
f()
// ➔ 2

Each call of an enclosing function creates fresh bindings, so closures made by separate calls have separate state, while closures made by the same call share it:

function counter() {
let n = 0
function bump() scope { n = n + 1; n }
bump
}
let c1 = counter()
let c2 = counter()
(c1(), c1(), c2())
// ➔ (1, 2, 1)

c1 and c2 count independently.

bump writes to n, which belongs to the enclosing call rather than to bump itself. Writing to a binding outside the function is the scope effect, and it must be declared — without the specifier the definition is rejected and counter() never produces a callable. See Effect specifiers. A local of the function body is declared with let: each call gets its own binding, a later declaration of the same name is not written, and it is not the scope effect (see Reassignment vs. declaration):

function step(k) { let s = k * 2; s + 1 }
let s = 10
(step(1), step(2), s)
// ➔ (3, 5, 10)

A read of such a local before its declaration in the function body (function step(k) { let r = s; let s = k; r }) is the read-before-declaration error, and an assignment to a name that is not declared (function g(c) { if c { t = 1 }; t }) is the assignment-to-undeclared-variable error; epsil check reports both before the program runs.

Reach for const when a name should not move at all. Constness is a property of the binding, not of the value it holds — every value is immutable already — and writing to one yields an Error value rather than quietly taking effect:

const c = 1
c = 2

Arguments are values — unless the function holds them​

A call evaluates its arguments first and hands the function their values: with let a = 3, f(a + 1) receives 4. A function declared with the hold prefix instead receives each argument as written — canonicalized and bound in the caller's scope, but not evaluated — and evaluates it only where its body reads it, so it can inspect the expression (head(e)), transform it, or decide whether to evaluate it at all:

let a = 3
hold f(e) = head(e)
f(a + 1)
// ➔ Add

Every parameter of a hold function is held (there is no per-parameter form), and a parameter read twice is evaluated twice — read it once into a let when that matters. See Hold functions.

Collections: literals are values, pipelines are generators​

A collection literal — a list […], set set(…), tuple (…), or dictionary — evaluates its elements when the statement executes. Assigning one to a variable stores a snapshot of the element values:

let k = 1
let xs = [k, k + 1]
k = 10
xs
// ➔ [1, 2]

A spread inside a list literal, [...xs, k], is a snapshot too: the literal holds the elements of each finite spread operand, also of a lazy one such as take(xs, 2). Only an infinite spread ([...1..oo]) stays a lazy list. See the Style Guide before growing a list in a loop.

let ys = [1, 2, 3, 4]
[...take(ys, 1), 9, ...drop(ys, 2)]
// ➔ [1, 9, 3, 4]

Lazy collection operators — Range, map, filter, take, join — are generators: their operands (bounds, sources, functions) are evaluated when the expression is, but enumeration is deferred until the collection is materialized (displayed, indexed, aggregated, or iterated).

An assignment is a snapshot for them too. When the right-hand side of a let or an = is a finite lazy collection that reads a variable, the statement stores the list of its elements, computed with the values the variables have at that statement:

let xs = [1, 2, 3]
let ys = filter(xs, c => c > 1)
xs = filter(xs, c => c > 2)
(xs, ys)
// ➔ ([3], [2, 3])

Two lazy collections stay lazy when they are assigned: one with no last element (filter(1..oo, p)), which cannot be listed, and one that reads no variable (map(f, 1..1000000)), which nothing can change. A filter over a dictionary also stays lazy. Such a collection is made as a call is: a variable that is one of its operands (xs in filter(xs, p), f in map(f, xs)) gives the value that it holds at that statement, and its inline function is a closure. The closure reads a local of the block or the function that made the collection, and a global, when an element is computed, so a later assignment of the variable is seen:

let k = 3
let big = filter(1..oo, c => c > k)
k = 10
first(big)
// ➔ 11

To keep the elements that the collection has at a statement, list them there: a finite part of it is listed by listFrom.

let k = 3
let big = filter(1..oo, c => c > k)
let firsts = listFrom(take(big, 3))
k = 10
firsts
// ➔ [4, 5, 6]

A lazy collection that is not assigned (an argument, an operand) still reads program state at materialization time, like a generator in Python.

The value of a program, that is the value of its last statement, is a snapshot too. When the last statement gives a finite lazy collection, the program gives the list (or the set, or the dictionary) of its elements, so a host that shows the value shows the elements:

map(u => u + 1, [5, 6])
// ➔ [6, 7]

The elements are computed once, when the program runs. A range (1..4) stays a range, and a collection with no last element (map(f, 1..oo)) or with more elements than the materialization cap stays lazy. A lazy collection that a statement other than the last one gives is not listed: nothing reads its value.

The test "reads a variable" looks at the expression as written, and does not look inside a named user function. An inline function that reads a variable makes the map read it, so the assignment stores the elements. A named function that reads the same variable does not: the map stays lazy, and its elements are computed when they are read, with the value the variable has then.

let n = 1
let v = map((k) => k * n, 1..3)
n = 10
v
// ➔ [1, 2, 3]
let n = 1
function scale(k) { k * n }
let v = map(scale, 1..3)
n = 10
v
// ➔ [10, 20, 30]

To get the elements with the value of n at the let, write the function inline, or make a list literal of the elements: let v = [...map(scale, 1..3)] gives [1, 2, 3] after n = 10.

Arrays: cells that change in place​

An array is the one collection whose elements change in place. It holds a fixed number of cells, and a store writes a cell of the array: it does not build a new array, and it does not rebind a name. Every name that holds the array sees the store, because an array has an identity, as an object does:

let a = arrayFrom([1, 2, 3])
let b = a
a[1] = 7
(b[1], a == b, a == arrayFrom(a))
// ➔ (7, true, false)

The same statements with a list give (1, false) for (ys[1], xs == ys): xs[1] = 7 gives xs a new list, and ys keeps the old one. Use an array for a buffer that a loop writes many times (a raster, a table of a dynamic program, a sieve); use a list everywhere else.

Making an array​

arrayFrom(xs) makes a new array with the elements of the finite collection xs, and arrayFrom(xs, "type") gives the type of its cells. There is no array literal. Each evaluation makes a new array, also of the same source.

arrayFrom(repeat(0, 64000), "integer<0..255>")
// ➔ array<integer<0..255>> of 64000

The type of the cells chooses the storage:

Cell typeStorage
An integer type with a range, such as integer<0..255>One machine integer of 1, 2 or 4 bytes for each cell
realOne machine number for each cell
A tuple of four integers in 0..255 (a pixel)Four bytes for each cell
Any other typeOne value for each cell

An integer cell holds its value exactly. A real cell holds the machine number of the value, so a[1] = 1/3 reads back as 0.3333333333333333, where a list keeps 1/3; declare array<rational> or array<number> to keep exact values. Without the type, the cells take the element type that a variable initialized with xs takes: arrayFrom([1, 2, 3]) is an array<number>, with one value for each cell. A program gets machine cells only where it names their type.

A declared type does not give the cell type to the value: let px: array<integer<0..255>> = arrayFrom(repeat(0, n)) is the error incompatible-type, because arrayFrom(repeat(0, n)) is an array<number>. Name the type once with a type alias, and give it to arrayFrom:

type alias Byte = integer<0..255>
let px = arrayFrom(repeat(0, 4), "Byte")
px[1] = 200
px[2] += 55
listFrom(px)
// ➔ [200, 55, 0, 0]

A type alias is another name for the same type. A type declared with type is a new type whose values carry its name (type Byte = integer<0..255> makes Byte(1), and 0 is not a Byte), so arrayFrom(repeat(0, 4), "Byte") is then incompatible-type. The one declared type with machine cells is a tuple of four bytes:

type alias Byte = integer<0..255>
type Pixel = tuple<r: Byte, g: Byte, b: Byte, a: Byte>
let img = arrayFrom(repeat(Pixel(0, 0, 0, 255), 4), "Pixel")
img[2] = Pixel(255, 128, 0, 255)
(img[2].g, img[1].a)
// ➔ (128, 255)

A tuple is a value, so img[2].r = 9 is the error immutable-value-assignment: store a whole tuple in the cell.

A transparent alias of the same four-byte tuple takes plain tuples such as (255, 128, 0, 255) as cell values. Reads keep the field names from the cell type. Both img[2].g and img[2][2] read the second byte.

Reading an array​

An array is read as a list is: a[i] from 1, a[-1] the last cell, a range or a list of indexes gives a list of those cells now, and length(a) is the number of cells. listFrom(a) is a list of the cells now: a later store does not change it.

let a = arrayFrom([10, 20, 30, 40, 50], "integer")
(a[1], a[-1], a[2..4], length(a), listFrom(a))
// ➔ (10, 50, [20, 30, 40], 5, [10, 20, 30, 40, 50])

An index that is 0, not an integer or past the end reads NaN in a number cell, as for a list.

Storing in an array​

A store is an assignment to a cell, or a += of a cell. The base of the cell can be any expression that gives an array: a name, a field of an object, an element of a list of arrays.

type Screen = object{w: integer, pixels: array<integer<0..255>>}
let s = Screen(w: 2, pixels: arrayFrom(repeat(0, 4), "integer<0..255>"))
s.pixels[3] = 255
s.pixels[4] += 7
listFrom(s.pixels)
// ➔ [0, 0, 255, 7]
let m = [arrayFrom([1, 2]), arrayFrom([3, 4])]
m[2][1] = 30
m[1][2] += 10
[listFrom(m[1]), listFrom(m[2])]
// ➔ [[1, 12], [30, 4]]

m[2][1] = 30 stores in the array m[2], and m is not rebound. A store does not change the binding, so a constant that holds an array accepts it:

const a = arrayFrom([1, 2, 3])
a[2] = 9
listFrom(a)
// ➔ [1, 9, 3]

swap(a, b) exchanges the cells of two arrays of one cell type, with no cell copied. Each array keeps its identity: every name that held a still holds a, with the cells and the count that b had.

let a = arrayFrom([1, 2])
let b = arrayFrom([3, 4, 5])
let c = a
swap(a, b)
(listFrom(a), listFrom(b), listFrom(c), a == c)
// ➔ ([3, 4, 5], [1, 2], [3, 4, 5], true)

What an array is not​

An array is not a list and not a collection. The collection operators (sum, map, filter, sort, …) and arithmetic refuse it with incompatible-type; take a list of its cells first:

let a = arrayFrom([1, 2, 3])
sum(listFrom(a))
// ➔ 6

== compares identity, not cells: two arrays with the same cells are not equal. A store is checked when it runs:

  • an index that is 0, not an integer or past the end is the error out-of-range (a[4] = 1 when a has three cells): a store never grows the array;
  • a value that the cell type does not hold is the error incompatible-type (a[1] = 12 in an array<integer<0..9>>);
  • a store into an element of a value that is not an array is the error immutable-value-assignment: s.px[2] = 9 with px a list field of an object. Store a new value in the field, s.px = replaceAt(s.px, 2, 9), or declare the field an array, px: array<integer>.

Example: the sieve of Eratosthenes​

function primes(n: integer) {
let composite = arrayFrom(repeat(0, n), "integer<0..1>")
let found = []
for k in 2..n {
if composite[k] == 0 {
found = [...found, k]
let j = k * k
while j <= n {
composite[j] = 1
j += k
}
}
}
found
}
primes(30)
// ➔ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

Example: a step of the Game of Life​

The board is two arrays of the same size, one cell for each square, with the rows one after the other. step() writes each cell of next from the eight neighbors in cur, then exchanges the two arrays, so that cur holds the new board and next the old one, which the next step overwrites.

let w = 5
let h = 5
let cur = arrayFrom(repeat(0, w * h), "integer<0..1>")
let next = arrayFrom(repeat(0, w * h), "integer<0..1>")

// The cell at column x and row y, from 0, with wrapped indexes.
cell(x, y) = (y % h) * w + x % w + 1

function step() {
for y in 0..(h - 1) {
for x in 0..(w - 1) {
let n = 0
for dy in -1..1 {
for dx in -1..1 {
if dx != 0 || dy != 0 { n += cur[cell(x + dx, y + dy)] }
}
}
let alive = cur[cell(x, y)]
next[cell(x, y)] = if n == 3 || (alive == 1 && n == 2) { 1 } else { 0 }
}
}
swap(cur, next)
}

rows() = [listFrom(cur[(y * w + 1)..(y * w + w)]) for y in 0..(h - 1)]

// A blinker: three live cells in a row turn to a column.
for x in 1..3 { cur[cell(x, 2)] = 1 }
step()
rows()
// ➔ [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]

Errors are values​

Per Principles, "errors are values": a runtime problem — a type error, an out-of-domain argument, reassigning a const — becomes an Error value that propagates outward through the enclosing expressions and becomes their result, not a thrown exception. A program never throws to its host for an ordinary runtime problem. Each top-level statement fails on its own, so an invalid statement or a thrown runtime error does not prevent later siblings from running:

let z = "a" + 1
5
// ➔ 5, with diagnostics for the invalid statement

A nested block or function body stops at its error instead of continuing its remaining statements. Cancellation stops the program; it is not an ordinary statement failure.

Parse-time problems are different: a malformed program surfaces as a diagnostic, not as a value. So do the few execution-time problems that are really about the source, not the computation — a gated host pragma, or an #error directive (see below).

Because only the last statement's value is the program's result, an error value produced by an earlier statement would otherwise vanish silently. Each non-final statement that evaluates to an error value therefore also emits a runtime-error diagnostic — for example an assignment to an element past the end of a list (xs[5] = 9 when xs has three elements), or reassigning a library constant such as Pi. A same-program const write rejected during preparation is already reported by the static check and is not reported a second time at runtime.

The same applies inside a block: a statement of a loop body, a function body or an if branch whose value is discarded and holds an error is reported, once for each place in the source. So is the list of a for loop or comprehension header, which no statement holds: in for x in [1, 1 / "a", 3] { n = n + 1 } the loop runs three turns, and the list [1, 1 / "a", 3] is reported, also when the body does not use x. A header that is a variable (for x in xs) is not reported again: the statement that gave xs its value is. A comprehension is evaluated when its elements are read, so its header is reported only when the program reads the list. A map or filter also reads its list later, but a statement such as let ys = map((u) => u, [1, 1 / "a", 3]) is reported at once, because each read of ys gives the error.

A program constructs an error value of its own with RuntimeError:

⌘/Ctrl + Enter

The call evaluates to Error("zero-has-no-reciprocal"), which a caller takes apart with if let or match like any other error value. The argument is a code string, or an ErrorCode("code", details…) when the error carries data.

Do not write Error("…") for this. A written Error(…) is a static diagnostic — the node the engine itself inserts where a program is wrong, such as a type mismatch — and it marks the whole expression around it as invalid: a function whose body spells Error("neg") never gets defined. The two spellings make the distinction explicit: Error is a problem with the program, RuntimeError is a failure produced by running it.

Console input and output​

print writes its operands to the host console — the terminal for the command-line tools, the developer console in a browser — separated by spaces and followed by a newline. Strings print their content, without the quotes; every other value prints its ordinary textual form. It evaluates to nothing:

let x = 6
print("x is", x * 7)
// prints: x is 42

input reads one line of text and evaluates to it as a string, without the trailing newline. An optional operand is a prompt, displayed before reading. In a terminal it reads from the terminal (piped standard input works too); in a browser it opens the prompt() dialog. At end-of-input — or when the dialog is canceled — it evaluates to nothing; on a host with no interactive input at all, the call stays symbolic.

> let name = input("Who? ")
Who? Arno
> print("Hello,", name)
Hello, Arno

print and input are the lowercase spellings of the Print and Input operators, like sin for Sin — not keywords — so a local declaration of print shadows the command like any other library name. See Naming.

Pragma security​

#env(...) and #navigator(...) read state from the host process (or the browser) at parse time. Because a notebook document can be shared or opened in an unfamiliar environment, both are gated off by default:

#env("HOME")

by default produces a host-pragma-disabled diagnostic and no host read — the pragma evaluates to nothing. A host can opt back in and let #env/ #navigator read as documented in Pragmas.

The benign pragmas — #line, #column, #url, #filename, #date, #time — always work; they don't read anything sensitive from the host.

#error(...) never crashes the host embedding the program: it becomes an error-directive diagnostic, so a single bad cell is contained.

Interruptibility​

A host can give an evaluation an explicit time budget, and independent count-based bounds on iteration and recursion depth. A breached limit becomes an error value (or an evaluation-canceled diagnostic when it happens in a non-final statement) — see Execution for how a host sets one.

The two kinds of limit end differently:

  • An expired time budget ends the program. The budget is one deadline for the whole run, so once it has passed no later statement could run either: the statement that hit it becomes the last one executed, the program's value is its Error("Timeout exceeded", "timeout"), and the statements after it are not evaluated. Statements that completed before the expiry keep their effects. The deadline is checked before every statement (and before every statement of the static pass), so a program of many cheap statements is bounded too, not only one whose single statement runs long.
  • A breached count-based cap (iterationLimit, recursionLimit) is per-construct: the next statement gets a fresh allowance, so the program continues past it. The statement that breached evaluates to the error value, and — because a loop is imperative — whatever it assigned before the breach stays assigned. A program that reads such a variable afterwards therefore sees a partial result alongside the evaluation-canceled diagnostic.

An Epsil program has no iteration limit by default: a loop runs until it ends, and a program that does not end is a valid program. The time budget is the bound a host should use. The engine's own default iteration limit (1024 turns of a loop or of a lazy walk) is removed on an engine the first time it runs an Epsil program, and it stays removed for everything that engine evaluates afterwards, so that a lazy collection the program returns can be read in full.

let total = 0
for i in 1..5000 { total = total + i * 2 }
total
// ➔ 25005000

A host that wants a count-based bound assigns ce.iterationLimit before it runs a program. An assigned limit is kept and applies to Epsil programs: a loop that exceeds it stops with iteration-limit-exceeded, and the host must then surface diagnostics with value, because the variables the loop assigned hold a partial result. The recursion limit (256 nested calls of user functions by default) always applies.

These limits are cooperative. A browser that evaluates untrusted or potentially unbounded programs should run Epsil in a Web Worker it can terminate from the outside. See Execution Constraints for the complete cancellation model.