Skip to main content

Types

A type is what Epsil knows about a value before it computes with it: that 3 is an integer, that [1, 2, 3] is a list of three integers, that f takes a real and returns a real.

You get three things out of that knowledge, and they are the reason to care about types at all:

  • Mistakes are caught where you made them. A function that declares mass: real rejects a string at the call, instead of producing a puzzling symbolic result twenty lines later.
  • The right code runs. Types choose between the clauses of a multi-clause function, and let the engine pick an exact algorithm for an integer where it would need a numeric one for a float.
  • Your intent is written down. A signature is documentation that cannot go stale.

Types come from the Compute Engine type language, so anything expressible there — unions, intersections, tuples, records, function signatures, generic collections — can be written in an Epsil annotation. This page is about using them.

Every value already has a type​

You never have to introduce types into a program: they are there from the start. type reports the one a value has. For a number literal that is the most precise claim there is — the value itself:

⌘/Ctrl + Enter

A literal type sits inside its numeric tier — 42 is an integer, 2.5 a real — so a literal is accepted anywhere its tier is. An exact value no machine number holds — 1/3, √2, an astronomically large integer — has no literal type to report, so it is typed by the narrowest safe claim instead: its tier, narrowed by a range that encloses the value. type(1/3) reports rational<0.33..0.34> and type(sqrt(2)) reports real<1.4..1.5> — bounds wide enough to be certainly true, which is also what fixes the sign. And anything stored carries the tier: let n = 42 declares n: integer, and the radius example below infers real.

Collections carry the type of what is in them, and how many:

⌘/Ctrl + Enter

Numeric types form a tower — integer ⊂ rational ⊂ real ⊂ complex ⊂ number — and a value of a narrower type is accepted wherever a wider one is expected, with no conversion and no cast. An integer is a real, so a function declared f(x: real) takes 3 happily.

Every name in that tower up to complex means a finite number. The infinities and NaN are not in any of them: they have types of their own, infinity and nan, and only the top of the tower covers all three — number is complex, infinity and nan together. So f(x: real) takes 3 and rejects Infinity and NaN with an incompatible-type error, while f(x: number) takes all of them.

When to write an annotation​

The default is not to. Epsil infers a stable assignment contract for an unannotated variable. Numeric variables use number, so later numeric values can replace the initializer:

⌘/Ctrl + Enter

Writing let radius: real = 2.5 restricts later assignments to finite real values. Reach for an annotation when this restriction is part of the contract, or in the five situations below.

1. On the parameters of a function others will call​

This is the one that pays for itself. A parameter annotation is enforced at every call, so a wrong argument is reported at the boundary, naming both types:

function bmi(mass: real, height: real) -> real { mass / height^2 }
bmi("70", 1.8)

That call evaluates to Error(ErrorCode("incompatible-type", "real", "string")) — an error value pointing at the call site. Without the annotation the string would have flowed into the division and come back as something symbolic and mystifying.

An argument with no value yet is checked when it gets one. While its type does not show that it fits, the call stays unevaluated:

function twice(k: integer) { 2*k }
let r = twice(m) // twice(m)
let m = 1.5
r // Error(ErrorCode("incompatible-type", "integer", "1.5"), …)

At a parameter typed real or number, the body is applied to a name with no type and no value: with function f(x: real) { x^2 }, f(x) gives x^2.

A return annotation (-> integer) is recorded in the function's signature and shown by about. The value that a call returns is checked against it, and a value of another type is an incompatible-type error:

function half(n: integer) -> integer { n / 2 }
half(4) // 2
half(5) // Error(ErrorCode("incompatible-type", "integer", "rational<2.5..2.5>"), 5/2)

A returned value whose type could still be the return type passes: with function h(n) -> integer { n / 2 }, h(x) gives 1/2 * x.

2. To choose between clauses​

When a function has several clauses, parameter types are how a call finds the right one:

⌘/Ctrl + Enter

See Multiple clauses for how the most specific clause is selected.

3. To hold a mutable binding to a contract​

An annotation on a let constrains not just the initial value but every later write to that name. This is how to say "this counter stays an integer":

let count: integer = 0
count = 2.5

The assignment produces an incompatible-type error value and count keeps its old value. Without the annotation, assigning 2.5 simply widens the binding to a real — inference follows the values, and asks no questions.

4. When there is nothing to infer from​

An empty initializer establishes list<unknown> for a mutable binding. Later assignments do not refine its element contract:

⌘/Ctrl + Enter

Say what you mean instead:

⌘/Ctrl + Enter

An annotation also fixes a contract before a runtime value is available (let x: real). An unannotated declaration without an identifiable straight-line initialization remains unknown. A read before initialization is an error.

5. When the inferred type is not what you meant​

Mutable bindings keep the contract inferred from their initialization. Numeric initializers establish number; lists erase fixed lengths and widen their elements. An annotation supplies a different contract, such as real or list<integer>. Later assignments validate against that contract without changing it.

Where an annotation goes​

An annotation follows a : after the name being declared:

x: real
x: real = 5

Function parameters and return values take one too, in all three function spellings:

f(x: real, n: integer) -> real = x^n
function g(x: integer) -> integer { x + 1 }
(x: integer) => x + 1

A declaration whose annotation is a function type written out with named parameters binds those names too — the initializer is then the function's body, no => needed:

const f : (x: real) -> real = x^2 + 2x + 1

The names bind only when the signature is spelled at the declaration site (an alias never binds). See Function-type annotations.

Everything after the : is read as a type, not as an expression. That is why <, >, |, & and -> mean something different there than they do in ordinary code — in u: integer | boolean the | is a union, not a logical or, and in f: (real) -> real the arrow is a function type, not a KeyValuePair:

xs: list<integer>
f: (real) -> real
u: integer | boolean

A : that does not follow a declaration target is not an annotation at all, so this rule never reaches into the rest of your program.

Glyph type names​

The double-struck letters spell the primitive number types, as they do in Lean:

GlyphType
ℝreal
ℤinteger
ℚrational
ℂcomplex
ℕinteger<0..>
c: ℝ = 3
function f(x: ℝ, n: ℕ) -> ℂ { x^n }
xs: list<ℤ>

A glyph is an input spelling only: the type is the primitive it names, and serializes as such (ℝ<0..1> is real<0..1>). ℕ is already a range and takes no range of its own. In expression position the same glyphs are the set constants (3.1 ∈ ℝ); see Naming.

Named functions may also declare their effects, between the parameter list and the return type:

function roll(n: integer) random -> integer { random(1..n) }

Effect labels are part of the function type. See Effect specifiers for the syntax and the function type guide for how they affect subtyping.

When a type doesn't fit​

Type checking happens as the program runs, not in a separate pass beforehand. The practical consequences are worth knowing:

  • A type failure is an error value, not a thrown exception and not a refusal to run. The statement that failed evaluates to an Error; the statements around it still run.
  • A program with a type error still parses, so the formatter, the serializer and the editor tooling keep working on it.
  • Because errors are values, they flow: an error handed to another function usually comes back as an error, so the first genuine mismatch is the one to read.

Only an annotation that is not a valid type is caught earlier — see Diagnostics below.

How inference decides​

A name with no annotation gets its type from how it is used. The engine does not solve equations; it accumulates evidence and moves through the type lattice as more arrives. Using a name as an argument narrows it toward the parameter's type; assigning a value widens it to cover that value. A name first seen in x + 1 is provisionally a number — a working assumption, not a conclusion.

Two consequences follow, and both are usually what you want:

Inferred types are revisable. A guess incompatible with a later assignment is discarded in favor of the value's own type, and a function that referred to a name defined only later is re-derived once that definition appears — so the order you write your statements in does not change what the program means.

Annotated types are not. What you write is a commitment; only guesses move.

One inherited behavior can surprise you: evaluating a bare symbol as a boolean operand (And/Or/xor/Not) infers that symbol boolean for the lifetime of the engine, and a later numeric use of the same name then errors. The convention is to keep boolean-only names distinct — uppercase A, B, C is the usual choice.

Naming a type​

Once a shape shows up in more than one signature — or once two different things share a shape and must not be confused — it is worth giving it a name. A type statement does that. The name is usable by every annotation later in the program, and by later cells sharing the same engine.

There are two forms, and choosing between them is the main decision here.

type alias: a shorter name for the same thing​

An alias is an abbreviation. pair and tuple<number, number> are the same type, spelled two ways, and values move between them freely:

⌘/Ctrl + Enter

Use an alias when the only problem is that a type is long or repeated:

type alias grid = list<list<number>>
type alias handler = (string) -> nothing

type: a new, distinct type​

The bare form declares a type that is its own thing. Nothing that merely looks like the definition belongs to it — the definition says how values are built, not which existing values qualify:

⌘/Ctrl + Enter

Use it when the distinction matters more than the convenience: two quantities with the same representation that must never be mixed up, or a value you want to construct through one checked entry point.

Temperature scales are the canonical case. As nominal types, the units cannot be interchanged:

⌘/Ctrl + Enter

toF(fahrenheit(212)) is an incompatible-type error — the mistake you wanted caught. The price is visible in the body: because a celsius is not a number, the arithmetic needs a match to get at the value inside, and the result must be re-tagged on the way out.

Written with aliases instead, the same program computes just as well and protects nothing:

⌘/Ctrl + Enter

Both spellings are legitimate. The question to ask is whether you are naming a shape for readability, or drawing a line the engine should enforce.

type alias X = …type X = …
Relation to the definitionthe same typea new, distinct type
A plain value of the shapeacceptedrejected
Constructor X(…)checked cast, no tagbuilds and tags a value
Reading the partsordinary operationsmatch, or .field
Prints asthe underlying valueX(…)
Reach for it whenthe type is long/repeatedtwo things must not mix

Declaring a type​

Neither type nor alias is a reserved word. Only the statement-position shapes type name =, type name<, type alias name = and type alias name< are read as a type declaration, so type remains an ordinary identifier everywhere else — type: integer = 4 still declares a variable named type:

⌘/Ctrl + Enter

(And type alias = tuple<number, number>, with nothing between alias and =, declares a type named alias — legal, but not a spelling to reach for.)

Constructors​

A type declaration also declares a constructor: a function of the same name that builds values of the type. A tuple definition gives a constructor with one argument per field; any other definition gives a one-argument constructor:

⌘/Ctrl + Enter

The arguments are checked against the definition, so point(1) and point("a", 2) produce an error value rather than a malformed point.

A value built this way carries its type with it, wherever it goes:

⌘/Ctrl + Enter

An alias constructor is a checked cast instead of a tag: it validates the arguments against the definition and hands back the plain value.

⌘/Ctrl + Enter

A record definition auto-declares no constructor: a record's fields are named, so building one from positional arguments would silently depend on the order the fields happen to be written in. Write one instead — see constructor functions below. Until one is declared, calling the name reports a type-not-callable warning.

Constructor functions​

A function bearing a declared type's name — after the type statement — is that type's constructor function. The body computes the payload: a value that must satisfy the type's definition (for a record, exactly the definition's keys, each field matching its type). The engine checks the payload and tags it; the result is a value of the type. This is how a record-bodied type gets its constructor:

⌘/Ctrl + Enter

Constructor functions are not record-specific: one may be written for any definition, replacing the automatic constructor. This is the smart constructor idiom — the single place a value of the type can come into existence, so validation or normalization written there cannot be bypassed:

⌘/Ctrl + Enter

A value that already satisfies the definition can be handed to the constructor directly — one argument, checked and tagged, body skipped. That raw spelling is also how a constructed value prints and reads back (circle(1, 2, 3) prints as circle({x -> 1, y -> 2, r -> 3})), so a round trip injects the payload unchanged and a normalizing constructor's values stay equal after it.

Because the payload spelling must construct unchanged, a constructor's parameters have to be distinguishable from the payload itself: a function whose parameters could also be a valid payload — same number of arguments, types the definition overlaps — is rejected when it is declared. Use a different number of arguments, or annotate the parameters with types the definition body cannot mistake.

A constructor function may call itself, and returning its own constructed value passes it through unchanged. A function with a type's name declared before the type is an ordinary function — the later type statement then reports the usual conflict. And for an alias, a same-name function is just an ordinary function: there is no tag to apply.

Values of a new type are opaque​

A point is not the tuple it is defined from — that is what makes it a new type, and what makes the mix-ups it prevents impossible. The same reserve means a plain tuple is not accepted where a point is expected, and the operations that take a tuple apart do not reach inside one:

type point = tuple<x: number, y: number>
let q: point = (1, 2) // error: a tuple is not a point
let p = point(1, 2)
first(p) // error
let (a, b) = p // error

Each of those lines parses: the rejection happens when the program runs, as an error value, not as a parse error.

There are two ways in. To take the value apart all at once, use match on the constructor — a constructor pattern is an ordinary operator pattern, and binds one variable per field:

⌘/Ctrl + Enter

To read a single named field, use the . accessor. It works on values of a declared type whose definition has named fields — a record body or a named-tuple body — and on records and dictionaries generally:

⌘/Ctrl + Enter

A type defined as another declared type has the fields of that type, and the accessor reads them through both layers:

⌘/Ctrl + Enter

On a dictionary, d.x is exactly d["x"], absent-key behavior included. On a record, a field that the type does not list is refused (see records and dictionaries). The accessor reads one named field through the type's definition; it does not make the value a collection — first(p), p["x"] and destructuring keep rejecting. (The dot must touch the value it reads: p.x is a field access, p .x is not; and a number never takes a field — 2.x is a multiplication.)

The spread copies the fields of a value of a declared record type into a new record: {...f, kind -> "x"}. The copy is a plain record, not a value of the declared type, because only the constructor makes a value of the type. (dictionaryFrom, which the spread is a short form of, also reads the fields of such a value in its list.) To get a value of the type, give the copy to the constructor, which checks it:

⌘/Ctrl + Enter

An alias has none of this reserve — it is its definition, so an alias-typed value works anywhere the underlying shape works:

⌘/Ctrl + Enter

Equality​

Two values built by the same constructor are equal when their arguments are. Values built by different constructors are never equal, and neither is a constructed value and a plain one of the same shape.

⌘/Ctrl + Enter

Epsil warns when a nominal tuple value is compared with a plain tuple. The comparison still runs. Use a value of the same nominal type on each side to compare their fields.

type point = tuple<x: number, y: number>
point(1, 2) == (1, 2)
// ➔ false with a nominal-tuple-comparison warning

Types are global, and re-running a cell​

A type declaration — both the type name and its constructor — is global: it belongs to the whole program (and to later cells on the same engine), not to any block. A type name means the same thing everywhere it appears. Consequently a type statement is only allowed at the top level of a program. Inside a do block, a function body, an if branch or a loop body it is an error:

do {
type inner = tuple<number, number> // ✘ type-declaration-not-top-level
inner(3, 4)
}

Declare the type at the top level instead, and use it anywhere — inside blocks and function bodies included:

⌘/Ctrl + Enter

Re-running a type statement for a name that an earlier type statement declared replaces the earlier definition, constructor included — constructor functions too, since an edited definition may invalidate the old body; re-running the whole cell restores both. Re-running a function statement that declares a constructor replaces the constructor. A name declared some other way — a function of that name predating the type, or a type declared by the host application — is not replaced: the statement reports an error value and declares nothing.

A type statement registers its name as the program is prepared, which is why the statements after it — in the same program or in a later cell — can annotate with it. A type the host declares on its own is visible to a program the same way, constructor and all.

Types with parameters​

A type that is the same shape at several element types — a pair of somethings, a tree of somethings — takes a type parameter rather than being written out once per element type. The clause goes between the name and the =.

For an alias, the application expands transparently: Pair<integer> means exactly tuple<integer, integer>, and that expansion is what type displays and error messages show:

type alias Pair<T> = tuple<T, T>
let p: Pair<integer> = (1, 2)

A parameter may carry a ground bound, enforced wherever the alias is applied — including application to another clause's type variable, which is admitted when the variable's own bound satisfies the parameter's. One alias may therefore be built out of another:

type alias Keyed<T: number> = tuple<string, T>
type alias Table<T: integer> = list<Keyed<T>>
let rows: Table<integer> = [("a", 1), ("b", 2)]

A generic alias may not refer to itself, every parameter must be used in the body, and applying one without its arguments (a bare Pair) is an error. Unlike a plain alias, a generic one declares no constructor and claims nothing in the value namespace: a function of the same name is an ordinary function, declared before or after. A dependent alias snapshots the definitions it was built from: re-running the type statement for Keyed leaves table as it was until table's own statement is re-run too — which re-running the cell does.

A parameterized nominal type takes a clause the same way. The difference is what an application means: a nominal type is opaque, so tree<integer> is never expanded — which is exactly what lets its body mention itself:

⌘/Ctrl + Enter

The constructor is quantified — tree: (T, list<tree<T>>) -> tree<T> where T — so T is solved at each construction, from the arguments. Applying the type at the wrong arity — including a bare tree — is the same error as for an alias, and a parameter bound is enforced the same way.

Reading a field reads the definition instantiated at the application's arguments, so it comes back at the type the application supplied, not at T:

⌘/Ctrl + Enter

match is not a projection of the annotation — it binds values, so each capture comes back at the matched value's own type, usually narrower than the annotation's:

⌘/Ctrl + Enter

Variance​

A parameter may carry an in/out/inout marker saying how two applications relate: out (covariant) makes a tree<integer> usable where a tree<number> is expected, in (contravariant) reverses that, and inout (invariant) relates only identical arguments. The words are contextual, claimed only inside a clause. An alias takes no marker — it expands rather than relates.

type tree<out T> = tuple<value: T, children: list<tree<T>>>
type sink<in T> = tuple<accept: (T) -> nothing>

A parameter with no marker means out — declared, not inferred, and verified against the body like any written marker. Values are immutable, so covariance is sound, and it is what the common case (a payload container) wants; only the minority that consumes its parameter needs to say so. Because the default is declared, a body that uses its parameter in an input position does not quietly change the type's subtyping contract — it is a variance-violation naming the offending occurrence and the markers that would verify:

type events<T> = tuple<log: list<T>, notify: (T) -> nothing>

This statement parses, but declares nothing: it evaluates to an error value carrying a variance-violation. T appears in both an output position (log) and an input one (notify.(arg 1)), so events can only be inout — writing type events<inout T> = … accepts the definition, at the cost of events<integer> no longer being usable as an events<number>. inout verifies against any body: invariance promises nothing, so it is always sound, just less permissive.

One limitation follows from that. A construction solves its parameters from its arguments alone, and an annotation does not widen them: let t: tree<number> = tree(1, []) works only because the tree<integer> it builds is a tree<number> under out. For an explicitly inout or in parameter that step is not available, so such a type can only be constructed at exactly its argument type.

Optional payloads​

A type variable may stand in one arm of a union, which is what makes an optional payload expressible. The ground arm marks the case with no payload; here it is boolean, since a declared type cannot name missing (see Absence values):

⌘/Ctrl + Enter

Each construction takes exactly one arm. Taking the ground arm says nothing about T, so T is solved to never — the narrowest member of the family, and (under out) a subtype of every other:

⌘/Ctrl + Enter

Only one arm may mention a variable: with two open arms nothing at the construction site says which arm a value took, so neither variable could be solved. type both<T, U> = T | U therefore declares nothing — it evaluates to an error value carrying an unsupported-variable-position. A variable may not stand in an intersection or a negation at all; an intersection is usually a constraint written in the wrong place, and the error says so — write a bound (type box<T: number> = …) instead of T & number.

Generic functions​

A function definition takes a type-parameter clause between its name and its parameter list, and the quantified names scope over the definition's head (its parameters, effect specifier, and return type):

function swap<T, U>(x: T, y: U) -> tuple<U, T> { (y, x) }
swap(1, "a")

A type parameter may carry a ground bound (function g<T: number>(x: T) -> T), which is enforced at every call.

The same clause can be written as a trailing where clause instead of the <…> binder. The two spellings are synonyms, and the clause always comes last — after the effect specifier and after the return type:

function swap(x: T, y: U) -> tuple<U, T> where T, U { (y, x) }
function g(x: T) -> T where T: number { x }
function f(x: T) where T { x } // return type inferred
function tick(x: T) random -> T where T { x } // with an effect specifier
f(x: T) -> T where T = x + x // math definition form

A declaration has one binding site: it may carry a <…> clause or a where clause, never both. function f<T>(x: T) -> T where T: number is an error, not a bounded <T: number>.

A full-type annotation has no binder slot, so it always uses the where clause — let f: (T) -> T where T = x => x.

A clause variable can also stand for a length. Written in a collection's length slot (vector<real^N>, list<T^N>, matrix<T^(MxN)>), it is bound from the length of the argument and must agree wherever it appears: a dot product declared over two vectors of the same length rejects a call with mismatched lengths at the call, and a matrix product can state the shape of its result. The same variable used as a parameter or return type is the integer with that value, bound from a literal argument:

function dot(a: vector<real^N>, b: vector<real^N>) -> real where N { 0 }
function mm(a: matrix<T^(MxN)>, b: matrix<T^(NxP)>) -> matrix<T^(MxP)> where T, M, N, P { a }
function len(x: list<T^N>) -> N where T, N { 3 }
len([1, 2, 3]) // typed 3

With these declarations, dot([1, 2, 3], [4, 5]) is an error at the call: expected vector<real^3>, got vector<integer^2>.

An argument whose type states no length — a symbol declared list<real> — is accepted and checked when the value is known, as it is at a literal length such as vector<real^3>. A length variable may carry an integer bound (where N: integer<2..>); its default is integer<0..>, since the empty list has length 0. A named type may take a length parameter too: type perm<N> = list<integer^N> makes perm([2, 1, 3]) a perm<3>, and perm<3> and perm<4> are different types. Arithmetic between lengths (^(M+N)) is not supported.

Note that a function is generic only when it is declared generic. Nothing is silently generalized: x => x is a function on some inferred type, not an implicit "for all T".

Records and dictionaries​

A record type lists the fields of its values, and a value has exactly those fields: record{w: real, h: real} holds {w -> 2, h -> 3}, and not {w -> 2, h -> 3, d -> 1}. The type of a dictionary literal is the record of exactly its keys.

⌘/Ctrl + Enter

A field that a value can leave out is optional: write a ? after its type. A read of an optional field that the value leaves out gives the absent value of the field type — missing, or NaN for a numeric field — so ?? supplies a fallback:

⌘/Ctrl + Enter

A field that a declared record type does not list is not a field: with r: record{w: real, h: real}, r.d is refused before the program runs (unknown-field). Without a declaration, the type of a value only describes that value, and a key that the value does not have reads as absent, as for a dictionary. The type of a conditional that gives records with different fields lists the fields of both, and a field that one branch leaves out is optional:

⌘/Ctrl + Enter

A record is a value: it does not change. A new field, or a new value for a field, is a copy made with the spread ({...p, z -> 3}), and deleteAt(p, key) is a copy without the key. The type of the copy follows:

⌘/Ctrl + Enter

A dictionary has any keys, with values of one type: declare it dictionary<V> when a program reads keys that are not known in advance. A key that it does not have reads as the absent value of V:

⌘/Ctrl + Enter

A record type is a dictionary<V> when every field type, optional fields too, is a V: a function that takes a dictionary<integer> takes {a -> 1, b -> 2}.

Absence values​

Epsil distinguishes three related kinds of absence:

  • nothing is the value of an empty block or of a statement with no value. It is kept as an element, in function arguments and collection literals too: [1, nothing] has two elements.
  • missing is a position-preserving missing value. Its type is missing. It is a result only: a selection with no match, a read past the end of a collection, or the written missing. A declared type cannot name it.
  • NaN is the numeric form of an absent or undefined result. Its type is nan, which sits outside real and complex and inside number. A read past the end of a list of numbers and a missing numeric field give NaN; a read past the end of a list of points gives a point whose coordinates are NaN.

isMissing(x) recognizes both missing and NaN, regardless of how the value arose. Coalesce(a, b, ...) evaluates from left to right and returns the first value that is not missing; if every argument is missing, it returns the last one unchanged.

⌘/Ctrl + Enter

A missing dictionary field follows the expected value domain: a numeric field produces NaN, while a string or other nonnumeric field produces missing. Use isMissing when the distinction between those representations is not important, and ?? — the operator form of Coalesce — to supply a fallback.

Three ways read a possibly absent value:

  • x ?? fallback replaces an absent value;
  • if isMissing(x) { … } else { … } branches, and the symbol is known present in the else branch (and after !isMissing(x) && in a condition);
  • x?! asserts that x is present and fails with an expected-present error when it is not. Use it where absence is a violated precondition rather than a case to handle.

A default parameter is not a reader: (k: real = 2) => k gives 2 when the argument is left out, and only then. A missing argument is passed to the body (g(first([])) is missing for g = (k: real = 2) => k + 1), and so is a NaN argument. Write g(x ?? 2) to replace an absent argument.

A default is a constant: a number, a string, true, false, [], {}, a constant (a library constant, over: set = Integers, k: real = pi, or a symbol declared constant before the function is defined, such as a const written before it in the same program, with any value), or a symbol that the parameter type lists (mode: symbol<Auto> | symbol<Manual> = Auto). A call that leaves out the argument receives that value, as if it had written it. A default that names a variable ((k = n) => k), or a symbol that is not declared and that no symbol<…> parameter type lists, is a static error: write a constant, or pass the argument.

Read the absent value before you compute. In the interpreter, any other operator over missing gives missing (missing + 1 is missing), and a comparison gives False (missing > 0 is False), but compiled code promises only the readers above and the accessors that move a value without computing on it (xs[i], first, last, rest, length). Any other operator applied to a possibly absent value gives the target's own answer when the program is compiled (undefined > 0 is false in JavaScript), so isMissing(w > 0) can differ between the interpreter and compiled code, and isMissing(w) cannot.

A declared type is a contract on the present values the symbol takes, and it cannot name missing. let s: string | missing = … and xs: list<string | missing> are type-annotation-errors. A read is typed by the element it reads: with xs: list<string>, xs[i] is typed string, and it gives missing when i is past the end. A declaration accepts that value where its type accepts a present value: let y: string = xs[i] gives missing past the end, with no diagnostic, and so do let s: string = missing, a later s := missing, and let xs: list<string> = ["a", missing]. A value of another type is still refused: let s: string = 5 is an error. NaN is not absorbed this way: a number declaration admits it (let n: number = NaN, let n: number = zs[i] for zs: list<number>), but the types real, integer and complex hold finite values only, so let r: real = zs[i] for zs: list<real> is an incompatible-type error when i is past the end, since the read is NaN. Read the value first (zs[i]?!, zs[i] ?? 0, isMissing(zs[i])), or declare number.

⌘/Ctrl + Enter

Background: what kind of type system this is​

None of this section is needed to use Epsil — it is background for readers curious about why the system behaves the way it does.

Types form a lattice​

The foundation is subtyping: types are arranged in a hierarchy, and most questions the engine asks are of the form "is this type a subtype of that one?". The numeric tower — integer ⊂ rational ⊂ real ⊂ complex ⊂ number — is the familiar part; its one surprise is that every step up to complex is finite, so the infinities and NaN join only at number. Around it the type language adds unions (integer | boolean), range refinements (integer<0..10>), collections with element types (list<integer>, set<string>), tuples and records, and function signatures with effect labels.

Each arrow points from a subtype to its supertype: every type from integer up to complex holds finite numbers only, and infinity and nan meet them at number. never has no values and is below every type, including the ones not drawn here.

Any two types have a join (the narrowest type that covers both — the join of integer and real is real) and a meet (the widest type inside both). Joins and meets are the workhorses of the whole system: the type of a mixed list is the join of its element types, and inference is built out of these two moves.

It is not Hindley–Milner​

Languages in the ML family (OCaml, Haskell, Elm) use a different foundation, called Hindley–Milner: types are compared for equality and solved by unification, which buys two famous guarantees. Every expression has a principal type — a single most general type that every other valid type is a specialization of — and inference is whole-program: the compiler sees the finished program at once, and a use of a function far from its definition can determine the definition's type, with no annotations anywhere.

This system deliberately trades those guarantees away, for two reasons.

First, subtyping and principal types pull against each other. In Hindley–Milner, integer and real simply fail to unify; here, a function declared (T, T) -> T where T called with an integer and a real succeeds, solving T to their join (a real). That is the behavior mathematics wants — but once many types are valid for an expression, "the single most general one" stops being the useful answer, and the engine makes pragmatic choices instead.

Second, there is no "whole program" to infer over. A session is open-ended: definitions arrive one statement (or one cell) at a time, may refer to names defined later, and may be redefined. The engine therefore types what it has seen so far and refines as more arrives, rather than solving a closed program once.

In character the system is closer to TypeScript or Go than to ML: subtyping at the base, generics that are explicitly declared rather than silently inferred, and types solved locally rather than globally.

Generics are solved per call​

At each call of a generic function, the engine collects what the arguments say about each type variable and solves the variables on the spot, by joining that evidence; the call's result type comes from substituting the solution into the signature.

Subtyping also quietly absorbs a classic use of polymorphism: the empty list needs no "for all" type — it is simply list<never>, and since never is the bottom of the lattice (joining it with anything gives the other type back), join([], [1, 2]) comes out as list<integer> with no quantifier anywhere.

For the representation a type declaration lowers to, see Type declarations.

Diagnostics​

An invalid type inside an annotation position surfaces as a type-annotation-error diagnostic, offset-corrected to point at the offending token within the type text (not at the : or the declaration target):

x: notatype

produces a type-annotation-error diagnostic pointing at notatype.