Learn

Contents

Quick reference

Every construct of the eLucid8 language, each with an example and what it means. The Tutorial teaches them with programs and their answers; the reference for AI assistants has the same constructs in a compact form, and elucid8 guide prints it, with no network.

In the examples, x and y are data over t, g is data over t and x, k is a single value, sales is data over zone and month, quote and trade are data with timestamps (over q and t), stamp holds times in milliseconds (over t), clock is a clock input (over t) and order data with timestamps (over n), and model is an input over amount that the deployment may answer on demand. A test compiles every example on this page.

A whole program reads data, defines values from it, and may name what it writes out:

x = input("x", t : 6)
running = x fby.t running + next.t x
ratio = running / x
output("running") = running
output("ratio") = ratio
-- table x = t,value; 0,3; 1,1; 2,4; 3,0; 4,5; 5,9
-- expect output "running" over t = 0..5
-- expect output "ratio" over t = 0..5
-- expect running[t = 4] = 13
-- expect ratio[t = 3] = error division: division by zero

Open in playground

The -- lines after the program give its data (x is 3, 1, 4, 0, 5, 9), the outputs it writes (t from 0 to 5) and two of its answers.

Data in

ExampleWhat it means
x = input("x", t : 6)Data from outside over t, read from the channel "x", at positions 0 to 5, and eod beyond them; a position among them with no row is missing data (an error of kind missing). Where it comes from (a table, a file, a database, a program) is the deployment's.
k = input("k")An input that is a single value, with no dimensions.
r = input("r", tick : inf)An input with no end along tick, for as many rows as there are: eod past the last row along tick; searches and outputs along it cover the data so far, which grows as data arrive.
s = input("s", zone : inf, t : 3)zone : inf: its coordinates come from the data, whole numbers or texts, as many as there are. Every dimension of an input says its extent (inf, a count, a range or a list); one named alone is refused.
s = input("s", zone : {"north", "east"}, t : 3)zone bounded by a list: only these coordinates exist, in this order.

An input is the whole right side of its equation, and each channel is read once. Its data end only along a dimension declared inf (with whole numbers as its coordinates): past the last row along it, every point is eod. Along texts declared inf, a key the data never mention is eod. Inside a finite bound or list, a point with no row (or an empty cell) is missing data: an error of kind missing, at time 0 (an empty cell at its row's time; on an input whose times come from a coordinate, that coordinate's time). So write inf for "as many as there are", and a number only for exactly that many. An input with no rows is eod along each dimension with no end, and missing inside finite ones. The deployment's "fill" may give missing points a value instead (0 for sparse data where no row means nothing happened), not the program; past the end of the data a point is eod whatever it says. A file with no column for one of the input's dimensions is refused (exit code 3), with a message naming the columns it has.

Where an input's data comes from is its entry in deploy.json, never the program (Command reference):

Values and coordinates

ExampleWhat it means
v = 2 * xA value. Its dimensions are those its equation depends on (here t); they are never declared.
c = 3 * 4A value with no dimensions.
v along (t) = 2 * xA check of v's dimensions: the program compiles only if the compiler finds exactly t (listed in any order; c along () = 3 for none), else the error names each extra dimension with the read that brought it in, and each one missing. Nothing else changes. Also on a local value, an input and an output, output("double") along (t) = 2 * x; not on a function.
n = 0 fby.t n + 1A value with no end along t: a dimension with no bound written has no end.
#tThe current coordinate on t (0, 1, 2, …).
x[t = #t - 1]x at another point: only t changes; a coordinate below 0 gives eod. Spaces never change the meaning: x [t = 0] is the same.
(x + y)[t = 0]Any expression at another point.
restrict g + 1 to (t : 10, x : 4) endg + 1 where t is below 10 and x below 4, eod (at time 0) elsewhere: a bound. It names only dimensions its expression has, and leaves the others open.
restrict x to (t : 2 .. 4) endA bound with a range, both ends included; also t : 2 .. inf, t : inf and lists such as t : {1, 3}.
"north"A text. Texts compare only with == and !=; anywhere else a number is needed, a text is an error.
"C" + "♯", "step " + text(3)+ joins two texts. A text and a number is an error that says to write text(n).
text(1 / 3), text(true)A number as elucid8 run writes it ("0.3333333333333333", "1e-7"), a boolean as true or false, a text as it is; a list, record or set is an error.
1e21, 2.5e-3Numbers with an exponent: the text of every number reads back as that number.
length("C♯4"), join(["C", "E"], " ")A text's number of characters (code points; here 3); a list of texts joined, with the separator between them ("C E").
"a \"b\""A text takes JSON's escapes: \" \\ \/ \b \f \n \r \t and \u00e9. Any other backslash, and a tab or line break written as it is, is a compile error.
sales[zone = "north"]A text coordinate: setting a text on zone makes zone a dimension of texts.
#zone == "north"Comparing the coordinate with a text also makes zone a dimension of texts. Each dimension holds whole numbers or texts, never both.

Literals and operators

ExampleWhat it means
3.5, -2Numbers (64-bit floating point).
true, falseBooleans.
eodEnd of data: there is none here. It is not zero, false or null: an operator with an eod operand gives eod.
error("too high")An error with that message.
x + y * 2, x - y / 4Arithmetic, * and / before + and -. Division by zero is an error, and so is any result that is infinite or not a number.
x < y, x <= y, x == 3, x != y, x >= y, x > yComparisons; not chained (a < b < c is refused).
x > 1 and not (y > 1) or x == 0Logic: and and or stop at a left operand that decides, without evaluating the right one.
if x > 2 then x else 0A conditional: only the branch taken is evaluated. The condition must be a boolean.
iseod(x), iserror(x)True or false, never eod or an error.
iserror(x, "missing")True for an error of that kind only: missing (an input's point with no row, or an empty cell), late, failed (a data service or a connector), division (by zero), non-finite, empty (mean, min, max or a statistic of no elements; head or tail of []), assert (a failed check), type (a value of the wrong sort, such as 1 + "a"), index (a list position outside the list, a record without the field), data (an error: … cell in the data), raised (error("…")), version (a pinned input version no longer available). An error passed on has its origin's kind.
x assert x >= 0x where the condition is true; an error of kind assert where it is false or eod (assert failed: x >= 0 was false). The condition is checked first; assert binds more loosely than everything but in, if and fby included.

Operators and functions are strict: an eod or error operand gives eod or an error, and eod wins when both occur.

Streams along a dimension

ExampleWhat it means
first.t xx at t = 0, the same at every t. first
next.t xx one position ahead along t. next
x fby.t y"Followed by": x at t = 0, and at every later t, y read one step back. fby
total = x fby.t total + next.t xA running total: a value that names itself in fby's right operand reads itself one step back. fby
fib = restrict 0 fby.n (1 fby.n (fib + next.n fib)) to (n : 100) endAn iteration that looks further back, by nesting fby. fby
x wvr.t (y > 2)"Whenever": at t, x at the (t + 1)th position along t where y > 2. wvr
x asa.t (y > 2)"As soon as": x at the first position along t where y > 2, the same at every t. asa
x upon.t (y > 2)At t, x at the number of positions before t where y > 2. upon

Precedence, the walk of wvr, asa and upon along t, and every other rule: Streams.

Regions and aggregates

ExampleWhat it means
sum x over (t : 0 .. #t) endThe sum of x from 0 to the current t. A region also supplies the coordinates it ranges over.
mean g over (x : #x - 1 .. #x + 1) endThe mean of g at x and its two neighbours. Positions below 0 or past the bound of what is aggregated are left out.
sum x over (t : 6) endOver positions 0 to 5; the result has no dimension t.
sum x over (t : 2 .. 4) endOver positions 2 to 4, both included.
sum x over (t : 2 .. inf) endFrom position 2 on, up to the bound of x. A region with no end over something with no bound there is refused.
sum x over (t : inf) endEvery position of x.
sum x over (t : {1, 3, 5}) endThe positions listed, in the order written.
sum sales over (zone : {"north", "east"}) endThe coordinates listed, here texts.
sum sales over (zone) endA dimension named alone: the coordinates the data has along zone (numbers ascending, then texts); where sales has no data, left out. In a restriction, a dimension named alone is open.
sum g over (t : 10, x : 4) endA region over several dimensions.
sum x over (t : 6) if x > 3 endA filter: positions where the condition is false or eod are left out.
mean x over (t : 6) skip eod endskip eod leaves eod elements out; otherwise one eod element makes the result eod.
mean x over (t : 6) endMissing data (errors of kind missing) is left out of every aggregate, neighbourhood and window, and the answer warns how many points it left out of each input. If every element it had was missing, the result is missing (sum x over (t : 1 .. 2) end with no data at t = 1 and 2); with no elements at all, sum and count give 0. sum x over (t : 6) skip missing end gives the same answer without the warning, where the gaps are expected; on a search, asof.t x at T skip missing end passes over missing points.
sum x * y over (t : 6) endThe exact sum of the exact products, rounded once; of any number of factors, sum x * y * z over (t : 6) end. Three or more factors in place are computed point by point, much slower on a large region; for speed, name the product, p = x * y * z, then sum p over (t : 6) end (each product rounded once, so the last place may differ).
mean x over (t : 6) end, min x over (t : 6) end, max x over (t : 6) end, count x over (t : 6) endThe other aggregates. With no elements, sum and count give 0, and mean, min, max, argmax, argmin and the statistics an error of kind empty: mean x over (t : 3 .. 2) end is "mean of no elements", and default(mean x over (t : 3 .. 2) end, 0, "empty") is 0. Two-argument default fills eod only, so default(mean … end, 0) around any of these, or around a name or function defined as one, compiles with a warning that gives the three-argument form.
variance x over (t : 6) end, sample_variance x over (t : 6) end, stddev x over (t : 6) endVariance (divided by the count), sample variance (divided by one fewer), and the standard deviation (the square root of variance).
argmax.t x over (t : 6) end, argmin.t x over (t : 6) endThe coordinate along t of the largest (smallest) element ("the day of the peak"; max gives the peak itself); the first, if several are equal. Over (t : 3 .. 5) it is a coordinate from 3 to 5, not a place in the range; along a text dimension, a name. Missing data is left out; an eod element makes it eod, unless skip eod.
approx_sum x over (t : 6) end, approx_mean x over (t : 6) endAdded in any order, for speed: the last digits may differ between machines and runs.
product x over (t : 6) end, approx_product x over (t : 6) endThe exact product, rounded once, whatever the order (1 over no elements); approx_product multiplies in the region's order, for speed. Both are computed point by point.

sum is the exact sum of its elements rounded once, and mean the exact sum divided by the count rounded once, whatever the order or the hardware. A region is not a value: it is written only after over, in an aggregate or a restriction.

Time and timestamps

ExampleWhat it means
time(x)The timestamp of x, in milliseconds: the time of the newest data it was computed from. eod where x is eod. Constants and coordinates have timestamp 0.
clock = input("clock", t : inf)The time now: an input given its rows by a clock ({"builtin": "clock", "every": "1s"} in deploy.json, under elucid8 serve), each tick's value and timestamp its UTC time in milliseconds. There is no now: a value that changed with the moment of asking would give two answers to one question.
waited = time(clock) - time(order)How long ago order happened, at each tick of the clock.
asof.q quote at time(trade) endThe quote at the position along q with the latest timestamp at or before the trade's time (of equal timestamps, the greater position).
asof.q quote at time(trade) within 5min endOnly quotes with timestamps in the last 5 minutes before the trade's time count.
asof.q quote at time(trade) skip eod endQuotes that say eod are left out.
hold.q quote at time(trade) within 5min endThe latest quote with data from the last 5 minutes: the same as asof … within 5min skip eod.
latest.q quote at time(trade) endThe last position along q whose timestamp is at most the trade's time; eod if there is none. Also with within (stale: missing data, as hold) and skip eod.
after.q quote at time(trade) endThe first position along q whose timestamp is later than the trade's time; eod if there is none. Also with skip eod.
after.q quote at time(trade) within 1min endThe first position whose timestamp is in the minute after the trade's time; eod if there is none.
sum trade over (t : window.t 5min at time(trade)) endA window: the positions along t with timestamps after the time less 5 minutes, and at or before the time. Any eod among them makes the result eod, unless the aggregate says skip eod.
250ms, 30s, 5min, 2h, 1d, 1wDurations, in milliseconds (5min is 300000).
utc("2026-10-18T12:00:00Z")A moment, in milliseconds since 1970-01-01T00:00Z.
utc_text(time(order))A time as ISO 8601 text in UTC, "2026-11-21T14:05:00Z", with .250 before the Z when the millisecond is not 0; utc reads it back. Not a whole number of milliseconds in the years 0000 to 9999: an error of kind type.

A searched value must be bounded along the dimension searched. A computed value's timestamp is the latest of what it read: for if, the condition and the branch taken; for an aggregate, every element and its bounds.

Functions

ExampleWhat it means
exp(x), log(x), sqrt(x), tanh(x), sin(x), cos(x), abs(x)Maths functions of one argument; log is the natural logarithm. The same bits on every machine.
tan(x), asin(x), acos(x), atan(x)Tangent, and the angle (in radians) back from a sine, cosine or tangent.
sinpi(x), cospi(x), tanpi(x)sin(πx), cos(πx) and tan(πx), with πx exact: sinpi(1) is exactly 0, cospi(0.5) exactly 0.
degrees(x), radians(x)Radians to degrees and back: radians(180) is pi.
log10(x), log2(x), log1p(x), expm1(x), cbrt(x)Logarithms in base 10 and base 2 (log2(1024) is exactly 10); log(1 + x) and exp(x) − 1, accurate for tiny x; the cube root.
fp32(x), fp16(x), bf16(x), fp8_e4m3(x), fp8_e5m2(x)The nearest value of a narrower format (IEEE single and half precision, bfloat16, and the two 8-bit formats), as a 64-bit number; halfway, the value whose last bit is 0: fp8_e4m3(100) is 96. Past the format's largest value (448 for fp8_e4m3, 65504 for fp16) an error, as IEEE 754's conversion gives infinity (or, for fp8_e4m3, not a number).
pi, tau, e, phiConstants: the doubles nearest π, 2π, e and the golden ratio. Nothing may be named after them.
floor(x), ceil(x), trunc(x), round(x), sign(x)Rounding, and the sign; round takes halves away from zero.
min(x, y), max(x, y), pow(x, 2), atan2(y, x), hypot(x, y)Functions of two arguments; hypot(x, y) is √(x² + y²) without overflowing on the way.
div(x, 3), mod(x, 3)Floor division and its remainder; mod has the sign of the divisor (mod(-5, 3) is 1).
default(x, 0)0 where x is eod, else x (an error stays an error).
year(stamp), month(stamp), day_of_month(stamp), day_of_week(stamp), hour_of_day(stamp), start_of_day(stamp), start_of_month(stamp)Date fields of a time in milliseconds, in UTC; day_of_week is 1 for Monday.
tab_focus(x, "Tab", false, "canvas", "tool", "file", false, "canvas")The node with focus after a window's event: tab_focus(kind, key, shift, node, next, prev, takes, before) moves it to next on Tab and prev on Shift-Tab, to the node pressed if it takes focus, and otherwise leaves it at before.
follow(y, x, 10)The first line to show: follow(scrolled, cursor, rows) is the user's scroll scrolled, unless the cursor moved after it (by their timestamps); then the least change that shows cursor with two lines to spare in rows lines.
editor = input("editor", t : inf, line : inf, col : inf)A code editor's document, with "editor": true on its text node in deploy.json: at each turn, the document after that turn's change, one code point a cell, eod past a line's end and below the last line. The window answers it; the change itself is the row of kind "edit" on the window's event input (from, removed, length).
fun prev(v) = v fby.t vA function, written at the top level. It applies to whole histories: prev(x) is x one step back.
fun before.d(v) = v[d = #d - 1]A function along a dimension the caller chooses: before.t(x) is x one step back along t.
fun lag.a,b(v) = v[a = #a - 1, b = #b - 1]Several dimensions the caller chooses, after one dot and separated by commas: lag.t,x(g) is g one step back along t and along x. A call's dimensions must differ from each other and from any the function names itself (lag.t,t(g) is refused).
fun scaled(v, k) = a * k where a = v + 1 endLocal values, in where … end.
y2 = a * a where a = x + 1 endA value may have local values too.
fun fac(n) = if n <= 1 then 1 else n * fac(n - 1)A function may call itself (and functions may call each other).

Built-in names (the functions above, sum and the other aggregates, true, false, eod) cannot be redefined with fun.

Programs over several files

ExampleWhat it means
s = "stats.el8"A name for the file stats.el8 beside the program; a path is relative to the file that writes it ("lib/stats.el8"). The example below shows stats.el8.
running in s, running in "stats.el8"The definition running of that file, named by a name for it or by the text itself. The program is as if the file's definitions were copied in, each named (running in "stats.el8"): the same answers, and errors name the values that way.
running / x * 100 in sAny expression, evaluated in the file: every name before in is the file's (its running and its x).
x * (running in s), (running in s)[t = 4]in binds more loosely than every other operator, on both sides: to mix the program's names with the file's (here the program's x), or for a point, write parentheses. running + 1 in s is (running + 1) in s.
(clamp in s)(x, 0, 10)A function of the file, called on the program's x.

The file after in is a constant text: written in place, a name whose equation is a text, or such texts joined with + (lib = "lib/", running in lib + "stats.el8"). A file named twice, by any route, is one copy. A file reads only its own definitions, those of the files it names with in, and the library. Only what the program reaches is part of it, so only the inputs it reaches need data. Inputs are shared by name: x read by both files is one input, which every file must read the same way. Another file's output(…) lines apply only when it runs alone. Dimensions are shared: between a file and a file it reads, a dimension both name must be one of an input both read, or one the values read from the other file have; a function that works along a dimension of its own takes it as a parameter (fun total.d(v) = …, called (total in s).t(x)). A query may name another file's value: (running in s)[t = 4]. Files may read each other, and a file reads the program's own definitions by the program's file name ((scale in "main.el8")); all of them are one set of equations, so a value that depends on itself through files needs fby, as in one file. Refused, with the file and line: a name the file does not define; a file reading a name it does not define; a file that is not a constant text; one input read two ways; a dimension named in two files that neither an input both read nor a value read between them has. A warning, once per name in each in: a name before in that both the file writing it and the file named define (with scale defined in both, scale + running in s reads the file's scale and warns scale is defined here (…) and in stats.el8 (…); in scale + running in s it is stats.el8's scale; write scale + (running in s) for this file's), a filter's or an aggregate's condition included, and a parameter or local value, which is not seen before in); none for a name the expression binds itself (those r from L if … end), an input both declare, or an expression before in that is a name alone or wholly in parentheses.

Lists, records and sets

ExampleWhat it means
[1, 2, 3], []A list, and the empty list. Its elements are values (never eod or an error); a list has one timestamp.
{x: 1, y: 2}A record: named fields, separated by commas, written with the names in alphabetical order; {:} is the empty record.
{3, 1, 1}, {}A set (here {1, 3}: no order, no repeats), and the empty set.
head([1, 2]), tail([1, 2]), length([1, 2])The first element, the rest, and the number of elements (also of a set). head([]) is an error.
x :: [1, 2], [1] <> [2, 3], [5, 6] elt 1A list with x in front; two lists joined; the element at a position, from 0 (here 6).
{x: 1, y: 2}.y, {x: 1} xby {y: 2}A record's field; the record on the right with the fields it lacks taken from the left.
{1} + {2}, {1, 2} - {2}, {1, 2} ^ {2}, {1} <= {1, 2}, {1} < {1, 2}, {1, 2} > {1}Union, difference, intersection; subset, proper subset, proper superset (also >=).
x isin {1, 2}, x addto {1, 2}Whether x is an element of a set or a list; the set with x added.
elements([2, 1, 2]), enumeration({2, 1})A list's elements as a set; a set's elements as a list, in order.
codes("abc"), from_codes([104, 105])A text's code points as a list, and back (here "hi").
those r from [3, 8, 1] if r > 2 endThe elements for which the condition is true, in order (here [3, 8]).
those s from {3, 8, 1} if s > 2 endThe same for a set: the set of its elements for which it is true (here {3, 8}).
list x * 2 over (t : 3) end, collect x over (t : 3) endThe list of a value over a region, in its order, and their set (also with if and skip eod).
sum [1, 2, 3] elt #i over (i : 3) endAggregating a list's elements: lay it along a dimension with elt.

== and != compare lists, records and sets by their contents. Every operation is strict: an element that is eod makes the result eod, an error makes it that error. A list, record or set is never a coordinate.

Answered on demand, and outputs

ExampleWhat it means
risk = model[amount = x]Asking the input model at the point amount = x. Where the deployment answers it on demand (an AI model, a web API, a simulator), each point is a question, asked only where an answer is wanted; an eod or error x means no question. The answer is stamped with the time it arrived; a late one is the error late. The deadline, retries and reuse are the input's settings in the deployment, not the program's.
output("report") = x + yAn output channel: the value written over its bounds, one record per point. Its right side is any expression; no equation may read it. From 0.22.0, a program may write a channel it reads; that output's default file is <channel>-output.csv.

Where each output goes, its format (CSV, JSON lines, Parquet, Arrow, NumPy, Zarr, frames, Vega-Lite, or Constant: each value written plainly, a line each), and which outputs with the same rows share a file side by side, are set in deploy.json (Command reference):

Comments start with -- and run to the end of the line.

Queries and messages name a point in brackets, as a program does: running[t = 4], running[t = 0..5] (both ends included), running[t = last] (the newest coordinate in the data), sales[zone = "north", month = 2]. A text is written in double quotes; an unquoted word is refused. A query names every dimension of its value, and so does an output's over in deploy.json; one that leaves a dimension out is refused.

Seeing a value in the playground: two dimensions make the picture, one may be played, the rest are held. The line under each view says which, in the program's terms: "heat: a stream of x × y pictures along time", "C: one i × j table".

Pictures you can zoom into: give the zoom a dimension of its own and halve the distance between points at each level, step = 0.005 / pow(2, #level), with x and y left with no end. The point (level L, x, y) is then the same place as (level L + 1, 2x, 2y), and + Zoom in, − Zoom out and a double-click ask the same program at another level (Pictures you can zoom into).

Not in the language: assignment, loops, mutation, indexing and slices ([d = c] only moves to another point; a list's element is L elt i), null, % (use mod), &&, ||, !, string functions and user-defined types. A program reads another eLucid8 file's definitions with in (above), never code in another language. The earlier forms x @ {t = 0} (write x[t = 0]) and (t : 10) | e (write restrict e to (t : 10) end) are refused with the form to write.

The playground on your computer

The playground on your computer (macOS, Windows and Linux) runs every program here on your own data:

Examples

Whole programs, from small to larger, each complete as written. The -- lines after a program give its data (-- table rows, separated by ;, or a -- data formula over the coordinates; a ts column holds each row's timestamp in milliseconds), and -- expect lines give some of its answers. A test runs every example and checks them; elucid8 check runs the -- expect lines too.

Simple

Counting to ten. The numbers 1 to 10, written by the elucid8 command on your computer, one a line.

x = 1 fby.t x + 1
output("x") = restrict x to (t : 10) end
-- expect output "x" over t = 0..9
-- expect x[t = 9] = 10

Open in playground

x is 1 at the first step, then one more at each step; the output writes its first ten. Save the program as count.el8, and this as deploy.json beside it: it sends the output x to standard output ("-"), each value plainly on a line of its own (Constant).

{ "format": "elucid8-deploy/2",
  "outputs": { "x": { "to": "-", "format": "txt" } } }

With the elucid8 command in the same folder (Deploy tutorial), run:

./elucid8 run count.el8 --config deploy.json

It prints:

1
2
3
4
5
6
7
8
9
10

Doubling. Each reading of x, times two; past the last reading there is none, so the answer is eod.

x = input("x", t : 5)
twice = 2 * x
-- table x = t,value; 0,3; 1,1; 2,4; 3,1; 4,5
-- expect twice[t = 2] = 8
-- expect twice[t = 5] = eod

Open in playground

Change since the previous step. How much x changed since the step before; at the first step there is no step before, so the change is eod.

x = input("x", t : 5)
change = x - x[t = #t - 1]
-- table x = t,value; 0,3; 1,1; 2,4; 3,1; 4,5
-- expect change[t = 0] = eod
-- expect change[t = 2] = 3

Open in playground

A counter. The number of steps along t: 0 at the first, then one more at each step, with no end.

n = 0 fby.t n + 1
-- expect n[t = 0] = 0
-- expect n[t = 7] = 7

Open in playground

A running total, as an iteration. The sum of x up to each step, each total from the one before.

x = input("x", t : 5)
total = x fby.t total + next.t x
-- table x = t,value; 0,3; 1,1; 2,4; 3,1; 4,5
-- expect total[t = 3] = 9
-- expect total[t = 4] = 14
-- expect total[t = 5] = eod

Open in playground

A running total, as a sum over the past. The same totals, each the sum of x from the first step to this one; past the data, the sum covers all of it.

x = input("x", t : 5)
total = sum x over (t : 0 .. #t) end
-- table x = t,value; 0,3; 1,1; 2,4; 3,1; 4,5
-- expect total[t = 3] = 9
-- expect total[t = 5] = 14

Open in playground

A 3-step moving average. The mean of x at this step and the two before; at the first steps, positions below 0 are left out.

x = input("x", t : 5)
avg3 = mean x over (t : #t - 2 .. #t) end
-- table x = t,value; 0,3; 1,1; 2,4; 3,1; 4,5
-- expect avg3[t = 0] = 3
-- expect avg3[t = 4] = 3.33333

Open in playground

A guard against division by zero. x divided by y, and 0 where y is 0, instead of an error.

x = input("x", t : 4)
y = input("y", t : 4)
ratio = if y == 0 then 0 else x / y
-- table x = t,value; 0,6; 1,6; 2,6; 3,6
-- table y = t,value; 0,2; 1,0; 2,3; 3,4
-- expect ratio[t = 0] = 3
-- expect ratio[t = 1] = 0

Open in playground

A missing reading filled with the previous one. The readings of x, with each missing one (a row the data do not have: an error of kind missing) replaced by the last reading before it.

x = input("x", t : 6)
filled = default(x, filled[t = #t - 1], "missing")
-- table x = t,value; 0,20; 1,21; 3,23; 5,24
-- expect x[t = 2] = error missing: input x has no data at this point
-- expect filled[t = 2] = 21
-- expect filled[t = 4] = 23

Open in playground

Fibonacci over a dimension. The Fibonacci numbers along n, each the sum of the two before.

fib = restrict 0 fby.n (1 fby.n (fib + next.n fib)) to (n : 100) end
-- expect fib[n = 10] = 55

Open in playground

Intermediate

Factorial, as a recursive function. The factorial of each n from 0 to 9, from a function that calls itself.

fun fac(k) = if k <= 1 then 1 else k * fac(k - 1)
f = restrict fac(#n) to (n : 10) end
-- expect f[n = 5] = 120
-- expect f[n = 9] = 362880

Open in playground

Row totals of a matrix. The total of each row i of the 3 × 4 matrix m, over its columns j.

m = input("m", i : 3, j : 4)
row_total = sum m over (j : 4) end
-- data m = 10 * #i + #j
-- expect row_total[i = 0] = 6
-- expect row_total[i = 2] = 86

Open in playground

A matrix product. The product of the 3 × 3 matrices a and b: each element the sum over k of row i of a times column j of b.

a = input("a", i : 3, k : 3)
b = input("b", k : 3, j : 3)
c = sum a * b over (k : 0 .. 2) end
-- data a = #i + #k
-- data b = #k - #j
-- expect c[i = 1, j = 2] = -4

Open in playground

Each zone's share, and the best zone. Each zone's share of the month's total sales, and, for each month, the zone that sold most, by name.

sales = input("sales", zone : {"north", "south", "east"}, month : 2)
total = sum sales over (zone : {"north", "south", "east"}) end
share = sales / total
best = argmax.zone sales over (zone : {"north", "south", "east"}) end
-- table sales = zone,month,value; north,0,10; south,0,30; east,0,60; north,1,50; south,1,20; east,1,30
-- expect share[zone = "south", month = 0] = 0.3
-- expect best[month = 0] = "east"
-- expect best[month = 1] = "north"

Open in playground

A file of definitions. stats.el8: a running total and a ratio of the readings x, and a function that keeps a value between two limits; it runs on its own, and then writes its output.

-- file stats.el8: a running total, a ratio and a clamp
x = input("x", t : 6)
fun clamp(v, lo, hi) = if v < lo then lo else if v > hi then hi else v
running = x fby.t (running + next.t x)
ratio = running / x
output("running") = running
-- table x = t,value; 0,3; 1,1; 2,4; 3,0; 4,5; 5,9
-- expect running[t = 4] = 13
-- expect output "running" over t = 0..5

Open in playground

A program over two files. A program that reads running, ratio and clamp of stats.el8, and computes pct wholly in it; x, read by both files, is one input.

-- A program over two files: definitions of stats.el8, read with in.
s = "stats.el8"
x = input("x", t : 6)
capped = (clamp in s)(running in s, 0, 10)
ratio = ratio in s
pct = running / x * 100 in s
-- table x = t,value; 0,3; 1,1; 2,4; 3,0; 4,5; 5,9
-- expect capped[t = 4] = 10
-- expect ratio[t = 3] = error division from (ratio in "stats.el8")[t = 3]: division by zero
-- expect pct[t = 4] = 260

Larger

Heat on a 16 × 16 plate. Heat spreading from a hot cell: at each step, every cell becomes the mean of the 3 × 3 block around it at the step before.

initial = input("initial", x : 16, y : 16)
heat = restrict
  initial fby.time mean heat over (x : #x - 1 .. #x + 1, y : #y - 1 .. #y + 1) end
  to (time : 1000, x : 16, y : 16) end
-- data initial = if #x == 8 and #y == 8 then 100 else 0
-- expect heat[time = 1, x = 8, y = 8] = 11.1111
-- expect heat[time = 5, x = 8, y = 8] = 4.40482

Open in playground

Trades priced as of their time. Each trade's price from the latest quote at or before its time, and how old that quote was, in milliseconds.

trade = input("trade", t : 3)
quote = input("quote", q : 4)
price = asof.q quote at time(trade) end
quote_time = restrict time(quote) to (q : 4) end
stale = time(trade) - asof.q quote_time at time(trade) end
-- table quote = q,value,ts; 0,100,1000; 1,101,4000; 2,99,9000; 3,102,15000
-- table trade = t,value,ts; 0,100.5,5000; 1,99.2,9500; 2,101.8,20000
-- expect price[t = 0] = 101, at time 5000 ms
-- expect stale[t = 0] = 1000, at time 5000 ms
-- expect price[t = 2] = 102, at time 20000 ms
-- expect stale[t = 2] = 5000, at time 20000 ms

Open in playground

Spend over the last 30 days. For each day, the sum of the purchases whose timestamps fall in the 30 days up to the start of that day; the hours with no purchase have no row, and a window passes over them (a point with no row has no time).

spend = input("spend", hour : 2400)
last30 = sum spend over (hour : window.hour 30d at #day * 1d) end
-- table spend = hour,value,ts; 10,20,36000000; 200,5,720000000; 800,12,2880000000; 1000,7,3600000000
-- expect last30[day = 10] = 25, at time 720000000 ms
-- expect last30[day = 50] = 19, at time 3600000000 ms

Open in playground

A thermostat. A room's temperature and its heater, each depending on the other: the heater is on while the room is below 20 degrees, and the temperature at each step follows the heater and the cold outside at the step before.

outside = input("outside", t : 10)
temp = 15 fby.t temp + (if heater then 1.5 else -0.5) + (outside - temp) / 10
heater = temp < 20
-- data outside = 5
-- expect temp[t = 3] = 16.355
-- expect heater[t = 3] = true

Open in playground

Anomaly detection. A reading is an alarm when it is more than 3 standard deviations from the mean of the 8 readings before it.

reading = input("reading", minute : 20)
mean8 = mean reading over (minute : #minute - 8 .. #minute - 1) end
spread = stddev reading over (minute : #minute - 8 .. #minute - 1) end
alarm = abs(reading - mean8) > 3 * spread
-- data reading = if #minute == 15 then 30 else 10 + mod(#minute, 3)
-- expect alarm[minute = 12] = false
-- expect alarm[minute = 15] = true

Open in playground

An AI scorer with a fallback rule. An AI model scores each payment for risk, within a 200 ms deadline; where its answer is late or fails, a simple rule decides instead.

payments = input("payments", t : 6)
fraud_model = input("fraud_model", amount : inf)
risk = fraud_model[amount = payments]
approve = if iserror(risk) then payments < 500 else risk < 70
-- table payments = t,value; 0,120; 1,1250; 2,40; 3,610; 4,2300; 5,75
-- service fraud_model: simulated score; takes 50 to 300 ms; fails 15% with overloaded; seed 3816; deadline 200 ms
-- expect risk[t = 0] = 55, at time 195 ms
-- expect risk[t = 1] = error late from fraud_model[amount = 1250]: late (257 ms > deadline 200 ms), at time 200 ms
-- expect approve[t = 1] = false, at time 200 ms

Open in playground

fraud_model is asked about each payment's amount, and answered on demand by a simulated model; its settings (how long it takes, how often it fails, its deadline) are the -- service line, the deployment's, not part of the program.

A running total written to a file. The readings and their running total as two outputs, which the deployment writes side by side to report.csv ("report.csv": {"channels": ["reading", "running"]}), one row per step.

x = input("x", t : 5)
running = x fby.t running + next.t x
output("reading") = x
output("running") = running
-- table x = t,value; 0,3; 1,1; 2,4; 3,1; 4,5
-- expect output "reading" over t = 0..4
-- expect output "running" over t = 0..4
-- expect running[t = 4] = 14

Open in playground