Skip to content

Records, variants, and function values

QVR has two structural data types over one row syntax: a record holds a value for every label of its row, and a variant holds a value for exactly one. A row may end in a row variable, which stands for the labels a computation does not name, so one computation accepts every record that has the fields it reads. Functions are values too: a computation may take a function, return one, or build one from a lambda that captures the values in scope. Every one of these forms is eliminated before a program reaches a backend, so each transpile target sees only first-order code (Export).

Rows

A row is a comma-separated list of labeled entries, optionally followed by | and a row variable:

Form Meaning
{prior : Real, facts : Int} record type with exactly the two fields
{prior : Real | r} record type with the field prior and the fields of r
{| r} record type with exactly the fields of r
<event, slider : Real> variant type with two alternatives; a bare label carries Unit
<slider : Real | r> variant type with the alternative slider and the alternatives of r

Labels within a row are distinct, and their order does not matter: {a : Int, b : Real} and {b : Real, a : Int} are the same type. A row variable is a static binder of kind Row, written in the brackets of a computation's telescope as [r : Row]. A row with no variable is closed.

Records

A record value lists its fields, and x.l reads the field l:

define weighted() : Real !{} =
    let j = {item = 3, response = 0.5}
    let wider = {j with weight = 2.0}
    let narrow = wider \ item
    let joined = narrow ++ {source = 1}
    return joined.weight * joined.response
example
expect weighted() == 1 exactly
Form Result
{l = v, m = w} the record with fields l and m
{x with l = v} x extended by the field l, which x must not have
x \ l x without the field l, which x must have
x ++ y the fields of x and of y, which must share no label
x.l the field l of x
let {l = a, m = b} = x bind the fields l and m of x to a and b

Extension never overwrites. A field is replaced by removing it and adding it again, (j \ response) ++ {response = 1.0}, so every record operation has one meaning whatever row its operands have. \ binds as tightly as *, and ++ as loosely as +. Extending a record by a label it has, or concatenating two records that share one, is refused with qiec-row-overlap, naming the shared labels.

A record declaration names a closed record type, with an optional static telescope:

record Judgment {item : Int, response : Real}

record Tagged[A : Type] {tag : Int, value : A}

define rescale(j : Judgment, by : Real) : Judgment !{} =
    return (j \ response) ++ {response = j.response * by}

define rescaled() : Real !{} =
    let j : Judgment = {item = 3, response = 0.5}
    let k <- rescale(j, 2.0)
    let t : Tagged[Real] = {tag = 1, value = 2.5}
    let {item = i, response = r} = k
    return r + t.value
example
expect rescaled() == 7/2 exactly

The declared name is an abbreviation: Judgment and {item : Int, response : Real} are the same type, so a record built anywhere with those fields is a Judgment.

Variants

<l = v> injects v at the alternative l, and <l> injects the unit value at a bare alternative. A case statement branches on the alternative, binding its payload:

define score(v : <event, slider : Real, scale : Int>) : Real !{} =
    case v
        event =>
            return 0.0
        slider(s) =>
            return s
        scale(k) =>
            return 1.0

define scored() : Real !{} =
    let a <- score(<slider = 0.75>)
    let b <- score(<event>)
    return a + b
example
expect scored() == 3/4 exactly

An injection has every variant type that has its alternative, so <event> is accepted wherever a wider variant is expected. A branch for every alternative of a closed variant is required, and a missing one is reported by name.

First-class cases

case { l(x) => e, m => f } is a function from a variant to the branches' common result type, and ++ joins two such functions over disjoint alternatives into one over their union. A case function written once is thus extended elsewhere without editing it:

define base_score() : <event, slider : Real * Real> -> Real !{} =
    return case { event => 0.0, slider(p) => p[0] + p[1] }

define extended_score() : <event, slider : Real * Real, graded : Real> -> Real !{} =
    let score <- base_score()
    return score ++ case { graded(g) => 10.0 * g }

The joined function dispatches each alternative to the side that handles it. Joining two cases that both handle one alternative is refused with qiec-row-overlap.

Extending a scorer from another module

A library exports a scorer for the response types it knows. A study that adds a response type imports the scorer and joins a case for the new alternative to it, without editing the library:

from quivers.dsl import loads
from quivers.qiec import invoke_entry

library = """
export define base_score() : <choice : Int, slider : Real> -> Real !{} =
    return case { choice(k) => 1.0 * k, slider(s) => 10.0 * s }
"""

study = loads(
    """
import ratings.scores as S

define graded_score() : <choice : Int, slider : Real, graded : Real * Real> -> Real !{} =
    let base <- S.base_score()
    return base ++ case { graded(g) => g[0] - g[1] }

define total() : Real !{} =
    let score <- graded_score()
    let a <- score(<choice = 2>)
    let b <- score(<slider = 0.25>)
    let c <- score(<graded = (0.75, 0.5)>)
    return a + b + c
""",
    modules={"ratings.scores": library},
)
assert float(invoke_entry(study.qiec, "total", ()).value) == 2.0 + 2.5 + 0.25

If the library later adds an alternative that the study also handles, the join is refused at the study's ++, naming the alternative both sides handle.

Row polymorphism

A computation that binds a row variable accepts every record or variant its parameter type admits. The row argument is inferred from the call's arguments, or written in brackets:

define response_of[r : Row](j : {response : Real | r}) : Real !{} =
    return j.response

define responses() : Real !{} =
    let a <- response_of({response = 0.5})
    let b <- response_of({response = 0.25, item = 3, weight = 2.0})
    let c <- response_of[{item : Int}]({response = 1.0, item = 4})
    return a + b + c
example
expect responses() == 7/4 exactly

A telescope may also state predicates over its rows, which the body may rely on and every call must satisfy:

Predicate Holds when
r ++ s ~ t r and s share no label and together are exactly t
{a : Real} <= r every entry of the left row is an entry of r, at the same type
define merge[r : Row, s : Row, t : Row, r ++ s ~ t](x : {| r}, y : {| s}) : {| t} !{} =
    return x ++ y

define total[r : Row, {a : Real, b : Real} <= r](x : {| r}) : Real !{} =
    return x.a + x.b

define merged() : Real !{} =
    let m <- merge({u = 10.0}, {v = 20.0})
    let t <- total({a = 1.0, b = 2.0, c = 3.0})
    return m.u + m.v + t
example
expect merged() == 33 exactly

A body that concatenates records at open rows needs the combination predicate that makes the result well formed; without it the checker asks for the combination to be stated. A call whose rows fail a predicate is refused at the call, naming the shared or missing labels.

Iterating over labels

Five operations range over every label of a closed row, so one definition compares, maps, or folds records and variants of any shape:

Form Result
fold_fields(x, init, acc -> l -> v -> e) e applied to the fields of the record x in label order, from init
map_fields(x, l -> v -> e) the record with the same labels whose field l is e
get_field(y, l) the field l of y, for a label l known before the program runs
case_alternatives(v, l -> p -> e) e at the alternative l that the variant v holds, with its payload p
if_alternative(w, l, q -> e, otherwise) e with the payload q when w holds the alternative l, and otherwise when it does not

In each function, l is the label as a string literal, so it may be returned, compared, or passed on to get_field and if_alternative. A computation that binds a row and uses one of these operations is generic: its body is elaborated once for each row it is called at, and only those instances, named NAME__fields_1, NAME__fields_2, and so on, enter the module:

define eq[r : Row](x : {| r}, y : {| r}) : Bool !{} =
    return fold_fields(x, true, acc -> l -> v -> acc && v == get_field(y, l))

define doubled[r : Row](x : {| r}) : {| r} !{} =
    return map_fields(x, l -> v -> v + v)

define same[r : Row](v : <| r>, w : <| r>) : Bool !{} =
    return case_alternatives(v, l -> p -> if_alternative(w, l, q -> p == q, false))

define generic_checks(v : <event, slider : Real, scale : Int>) : Bool !{} =
    let a <- eq({p = 1.0, q = 2}, {p = 1.0, q = 2})
    let b <- eq({flag = true}, {flag = false})
    let d <- doubled({w = 4.0, z = 0.5})
    let c <- same(v, <slider = 0.5>)
    return a && not b && c && d.w == 8.0

The body at each label is checked at that label's types, so v == get_field(y, l) compares reals at a Real field and integers at an Int field. Labels are visited in sorted order, whatever order a record was written in. Each iteration expands once per label, so the row must be closed where the iteration runs: a call that passes a generic computation a row ending in a row variable, or a field type that is still a static variable, is refused with qiec-row-open at the call, naming what is not yet known:

labels.qvr:15:13: [qiec-row-open] `eq` iterates over the labels of its rows, which needs a closed
row: every label is known only once each static argument is, but here 'r' is {a : Real | s}, whose
labels end in the row variable 's', known only where a caller fixes it

A generic computation may call another, or itself at smaller rows, such as at a field's own record type; a call to itself at rows no smaller than an instance in progress is refused, since its instances would not end. The derived instances of Eq, Show, and the other classes cover a family's constructors in the same way, generated in the meta phase from the family's description; these operations cover the labels of a row.

Function types and values

A -> B !{e} is the type of a function from A to B whose application may perform the effects in the row !{e}; A -> B alone is a pure function. A function of several arguments takes their product, A * B -> C, and is applied as f(a, b). The row may be open, !{| e}, so a computation that applies its argument performs whatever the argument does:

define twice(f : Real -> Real !{}, x : Real) : Real !{} =
    let y <- f(x)
    let z <- f(y)
    return z

define offset(by : Real) : Real -> Real !{} =
    return x -> x + by

define four() : Real !{} =
    let g <- offset(1.0)
    let r <- twice(g, 2.0)
    return r
example
expect four() == 4 exactly

A function value is a lambda, x -> body, which captures the values in scope (by above); a case { ... } function; a parameter or local of function type; or the name of a computation with no static arguments. A computation with static arguments is a function value where the expected function type determines them. Applying a function is a computation, bound with <-; applying a pure function inside a pure expression, as in map(xs, x -> f(x) + 1.0), runs the application first and uses its result.

In a result position, define f() : A -> B !{} = reads !{} as the row of f itself, as it always has, so f returns a pure function. A function result that performs effects writes both rows, A -> B !{e} !{}.

Local definitions

A where block after a computation's body holds definitions visible only in that body. They may read the computation's parameters and may call one another recursively:

define clipped_sum(xs : Real[Fin 3], bound : Real) : Real !{} =
    let total = fold(xs, 0.0, acc -> x -> acc + clip(x))
    return total
where
    define clip(x : Real) : Real !{} =
        if x > bound then
            return bound
        else
            return x

define parity(n : Int) : Bool !{} =
    let e <- even(n)
    return e
where
    define even(k : Int) : Bool !{} =
        if k == 0 then
            return true
        else
            let o <- odd(k - 1)
            return o
    define odd(k : Int) : Bool !{} =
        if k == 0 then
            return false
        else
            let e <- even(k - 1)
            return e
example
expect clipped_sum([1.0, 5.0, 2.0], 3.0) == 6 exactly
expect parity(4)
expect not parity(3)

Type inference

An unannotated lambda or case function bound with let is given its principal type, the most general type of which every other type it has is an instance. Field reads, extensions, restrictions, and injections each contribute a row with a fresh tail, and concatenation adds the predicate that its operands' rows combine:

Expression Principal type
x -> x.prior forall a r. {prior : a | r} -> a
x -> {x with weight = 1.0} forall r. {| r} -> {weight : Real | r}
x -> x \ weight forall a r. {weight : a | r} -> {| r}
x -> y -> (x \ a) ++ (y \ b) forall a r b s t. r ++ s ~ t => {a : a | r} -> {b : b | s} -> {| t}
s -> s ++ case { graded(g) => g } forall r a. (<| r> -> a) -> <graded : a | r> -> a

A binding is elaborated at the type of each use. A polymorphic function that is never used at a known type, such as one stored in a record field, is refused with its principal type in the message, so the annotation to write is in hand.

Export

The reference machine runs records, variants, and functions as written. Everything compiled or transpiled reads a first-order translation instead, which the checker validates like any module:

  1. Each computation with row binders or predicates is specialized at the closed rows of its calls, and its record and variant operations become positional operations whose offsets are read off the rows.
  2. Records become tuples, and each variant type becomes a generated family with one constructor per alternative.
  3. A function argument known at the call is specialized into a copy of the callee. A function chosen at run time becomes a constructor of a generated family __Closure_n holding its captured values, and each application becomes a case on that family.

A target without case on families, such as Stan, BUGS, or JAGS, therefore accepts every program whose functions are known at their calls and refuses one that chooses a function at run time, naming the capability it lacks. A computation of the module that takes a function keeps a general form beside its specializations, since it remains callable with any function. The semantics of rows and functions states the typing rules and why the translation preserves meaning.

Collection operations

map, fold, logsumexp_over, and traverse accept any function value in their function position, not only a lambda; see Finite collection expressions.