6. Functions, closures and generators
The normative CP Lang 0.3 specification.
This is the normative specification (source). For a gentler introduction, start with the guides.
Status: draft for 0.3.0. Ownership of captures and lends is chapter 5,
which is authoritative; this chapter gives the forms and their meaning.
Sources: archived design/spec/14-16, plan/15-program-structure.md;
decisions 126, 127, 129, 138, 141, 144.
6.1 Functions
fn dist(a: P, b: P) -> Int = abs(a.x - b.x) + abs(a.y - b.y)
fn solve(n: Int, mut seen: [V]Bool; limit: Int = 10) -> ?Int:
...- One-line
= expror a block whose last expression is the value.returnis for early exits. (R06.1.1) - Parameters are lent for the call;
mutparameters may be mutated (or drained) and are markedmutat the call:solve(n, mut seen). The method receiver needs no marker at the call. (R06.1.2) - A parameter of a
fnor a lambda may be a pattern, as infor:(mut d, (u, v)) => d.unite(u, v).mutmarks the whole parameter. (R06.1.3) - A lambda with k parameters, passed where the callee expects a function
of one k-tuple, unpacks it:
(V, V).all((u, v) => ...)anda.items.filter((i, x) => ...)mean((u, v)) =>and((i, x)) =>. The callee's function type decides; a lambda that wants the whole tuple takes one parameter (p => p.0). This is not overloading: the signature is fixed and only the lambda's spelling adapts (decision 159). (R06.1.4) - Named and positional arguments, defaults, named-only parameters after
;, and a variadic..xs: Tstuple parameter. Options are always named (by:,desc), never_bytwins (decision 60). (R06.1.5) - No overloading by type: one name and label set has one generic
signature (decision 127). Operators are functions:
fn (a: Frac) + (b: Frac) -> Frac. (R06.1.6) - Functions hoist within their block; every capture must be initialized before the first call. (R06.1.7)
- A
fnpassed where a function of fewer parameters is expected takes only those, when every omitted trailing parameter has a default; the defaults fill them:vis.map(yes)isvis.map(b => yes(b)). An omitted parameter without a default is a type mismatch (E0302). (R06.1.8)
6.2 Nested functions and lambdas
Nested fns and lambdas are the same thing for every rule; they differ
only in spelling (decision 144):
fn go(v: V): // nested fn: recursion by name
seen[v] = true
for u in g.next(v) if not seen[u]: go(u)
let fact = n => if n == 0: 1 else: n * fact(n - 1) // recursive lambda
xs.sort(by: p => (p.x, desc(p.y)))
on_remove: (v, a) => cnt[a] -= 1 // body may be an assignment
by: x => // block lambda
let k = key(x)
(k.0, -k.1)- Captures act as call-time arguments. A closure holds no lend
between calls: each call lends what it reads and mutably lends what it
writes, for the call's duration. So a closure may mutate captured
vars, two closures may capture the samevar, and the borrow rules are checked at each call site (chapter 5). (R06.2.1) - A captured variable cannot be moved while the closure is alive, and a
closure cannot outlive what it captures (it cannot be returned past
them, stored in an outer
var, or put in a longer-lived field). (R06.2.2) - A
let-bound lambda may call itself; avarbinding cannot. When recursion leaves the return type open, annotate:(n: Int) -> Int =>. (R06.2.3) - There is no
pureand nomut fnmarker. Purity that a library needs (lazymap,@memo) is a documented contract checked by lints and stress, not a type. (R06.2.4) - Function types are
(A, B) -> R. Every call with a known function value is specialized; there is no indirect call and nostd::function(chapter 13). (R06.2.5)
6.3 Generators
A generator is a function that pushes elements to its caller's loop body:
fn divisors(n: Int) -> yields Int:
for d in 1..=n.isqrt() if n % d == 0:
yield d
if d * d != n: yield n / d
for d in divisors(n): ...
let s = divisors(n).filter(d => d % 2 == 0).sum()- A generator value is a recipe: a call with every argument but the
loop body filled in. Nothing runs until something walks it (
for, a fold,.collect()), and each walk reruns it. Walking a value twice is legal; walking one that holds amutlend twice is linted. (R06.3.1) - A generator value built from lent arguments holds those lends until its last use, like a struct built from them (chapter 5). (R06.3.2)
- The loop body may
break,continue,return, use labels and loopelse, even when the generator is recursive (decision 126). A non-recursive generator inlines into the loop; a recursive one gets a hidden stop path only in specializations whose body can exit. (R06.3.3) - A body steers its generator through the yielded item, read after
yieldreturns:step.prune()skips a DFS subtree. Enter/exit walks yield events (Enter(v, via:),Exit(v, via:),Again(from, via)). (R06.3.4) - Generators are push-only; there is no cursor. Lockstep over two
generators is
List(g)first, a visible allocation. (R06.3.5) - Sequences, views, chains and capabilities are chapter 7.
6.4 Decorators
@d(args) before an item. The set is closed, each documented by its
library or by this spec:
@memo(array)/@memo(map): cache a function. The storage is spelled, never picked (round 3):arrayneeds every parameter typed by a bounded type (domain, cut, range,Bool, enum) and allocates the dense table on the first call,mapuses an open-addressing hash map. A parameter bound may mention earlier parameters (j: 0..=i); the table is then jagged. The cache lives as long as the declaring block (per test case at top level below@!multitest). A memo function may not do I/O or mutate captures; a write to something it captured while the cache lives is an error.cpl explainshows table bytes. (R06.4.1)@get: an O(1) read-only method called without parentheses. (R06.4.2)@test,@alt(f, caps),@gen,@check,@interactor: tool roles (tools/stress.md); the item is otherwise unchanged. (R06.4.3)@cacheon a struct field: compiler-safe interior mutability with an author promise of logical correctness (chapter 5 §10a). (R06.4.4)@trusted:blocks and@cppitems: the unsafe tier (chapter 9).@grader(...): judge entry points (chapter 10).@laws(sample: n): stress sampling of a type's laws.@tag(lit)on an enum variant: the token it reads and prints as (chapter 2).@droppable: the result may be dropped without the unused-result lint. Dropping a non-unit result is that lint (a warning); dropping a?Tis an error (see R02.4.7). (R06.4.8)
User libraries declare their own decorators as ordinary generic
functions over function types, and their own tool roles with marker
(chapter 12, W-list).
6.5 Where state lives
- Top-level bindings above
@!multitestare shared by every test case; everything below is per case, including@memocaches and fresh types. (R06.5.1) - A nested function is the way to split a long solution: each chunk is a
nested fn over the test's state. Any function is a part that stress
and
cpl locatecan test alone (tools/stress.md).