ilusm.dev

gen

Generic higher-order utilities - identity function, validated vector map/filter/fold, constrained box (value must satisfy a predicate), parallel zip-with, tagged union value, and lazy thunk (evaluate once on first access).

Load with: use gen

What this module does

gen provides the fundamental generic abstractions that sit underneath many other ilusm patterns. Its validated vector functions mirror trl's map/filter/fold but add type-checking guards. The box abstraction wraps a value with a predicate contract: creation and update both enforce that the value satisfies the predicate. The lazy abstraction wraps a thunk that is evaluated at most once, memoising the result for future calls.

Quick example

use gen

# Identity
prn(genid(42))  # 42

# Vector map (validates list and fn)
doubled = genve([1,2,3], \(x) x * 2)  # [2,4,6]

# Constrained box (only positive numbers)
b = genbo(\(x) x > 0, 5)
prn(genbo(b))        # 5
b2 = genbo(b, 10)    # update
# genbo(b, -1)       # error: T not satisfied

# Parallel zip-with
sums = genpa([1,2,3], [10,20,30], \(a,b) a+b)  # [11,22,33]

# Tagged value
t = genta("score", 95, \(v) v >= 0 and v <= 100)
prn(genta(t))  # 95

# Lazy thunk
lz = genla(\() 1 + 1)
prn(genla(lz))  # 2 (computed once)

Functions

Core

genid(x)

Returns x unchanged. The identity function.

Vector higher-order functions

genve(xs, fn) - map

Maps fn over list xs. Errors if either argument has the wrong type.

genve(xs, pred) - filter

Filters xs keeping elements for which predicate pred returns truthy.

genve(xs, z0, fn) - fold

Folds xs from left with initial accumulator z0 and combining function fn(acc, x).

genpa(xs, ys, f)

Parallel zip-with: applies f(xs[i], ys[i]) for each index. Errors if the lists have different lengths.

Box (constrained value)

genbo(T, v) - create

Creates a box holding value v constrained by predicate T. Errors if T(v) is falsy. Returns {T, v}.

genbo(box) - read

Returns the value held in the box.

genbo(box, v) - update

Returns a new box with value v, re-checking the predicate. Errors if the new value violates T.

Tagged value

genta(tag, val, pred) - create

Wraps val with a string tag and validates it against pred. Errors if pred(val) is falsy. Returns {tag, val}.

genta(tagged) - unwrap

Returns the val field from a tagged value.

Lazy thunk

genla(thunk) - create

Creates a lazy wrapper around a zero-argument function thunk. The thunk is not called yet. Returns {t:"lazy", th, v:nil, done:fls}.

genla(lazy) - force

Forces the lazy value. Calls the thunk on first access and memoises the result. Subsequent calls return the cached value without calling the thunk again.

Notes

  • Requires trl and eru.