7. Functions and closures
Function declarations
Section titled “Function declarations”Taught in Functions & Lambdas.
fn name(parameters) -> Result, the body on the lines below and end,
declares a function (§2 Bodies). A generic function writes its type
parameters after the name, and a where clause after the result:
fn shown<T>(x: T) -> String where T: Display. A long where clause goes on
the next line, which the where continues.
fn add(x: Int, y: Int) -> Int x + y end fn main() dbg add(1, 2) // 3 end
- Every parameter has a type. A missing type is
parameter 'x' needs a type annotation, in afn, an impl’s or an interface’s function and ahost fn; an impl’s parameters are written out, not taken from its interface. A parameter has a name too, unless it is written as its type alone,fn stats(Request), which takes aRequestand binds nothing (Parameter Destructuring). Only a lambda’s parameter types may be inferred. - The result type is written unless it is
Unit; a function with no->returnsUnit. - The body’s last expression is the result (Returning).
- A function’s or lambda’s body is a block for
defer(§9defer).
A fn, and a struct, enum, type, typealias or interface, may be
declared inside a body. It is visible in the rest of its block and the
blocks inside it (§6). A nested fn closes over the names in scope as a
lambda does, and takes no pub. A nested type’s name is a type in every
annotation of that block. An impl or a derive may not stand in a body:
an `impl` block must appear at module top-level, not inside a body, and
a `derive` declaration must appear at module top-level, not inside a body.
Nor may a subtype or a validated type (§4 Validated types).
Parameters
Section titled “Parameters”Default Arguments
Section titled “Default Arguments”Taught in Functions & Lambdas.
Any parameter may have a default, port: Int = 8080. A call that leaves the
argument out evaluates the default, after the written arguments, in
parameter order, once per call. A default may read earlier parameters and
the declaring file’s functions. A default is checked against its parameter’s
type: width: Int = "wide" is
default value for parameter 'width' is String, expected Int. A host fn’s
and a go binding’s default is Nomi code like a fn’s, evaluated before
the call leaves Nomi.
fn connect(host: String, port: Int = 8080, timeout: Int = 30) -> String "${host}:${port}/${timeout}" end fn main() dbg connect("x") // "x:8080/30" dbg connect("x", 80) // "x:80/30" dbg connect("x", timeout: 5) // "x:8080/5" end
Positional arguments fill parameters in order, so leaving out a default
that is not last means naming the arguments after it. middle(1, 2) for
fn middle(a: Int, b: Int = 10, c: Int) is
missing argument for parameter 'c'; positional arguments fill parameters in order and cannot skip the defaulted 'b', so pass this one by name (c: ...).
The one exception is a trailing callback (Lambdas at Call Sites).
A default is not part of the function’s body, so a ?, return, break,
continue or assertion written directly in it is an error at that token:
`?` cannot be used in the default of parameter 'x': a default has no function to return from.
A lambda’s defaults follow the same rule.
Defaults fill a call of the function by name, and a call through a local
name that copies it (below). A function used as a value has its full
parameter list, with one exception: where its position
expects a function type with fewer parameters, and each parameter past those
has a default, the value is the function of its first parameters, and a call
of it fills the rest from their defaults. That holds at an argument, a
pipe’s head (§8 Pipes), an annotated binding, a field, a list element, a
return and a case or if arm: where apply takes a (String) -> Maybe<Int>, parse |> apply("1") passes parse as apply(parse, "1")
does. A local copy is not the function’s name, so after g = parse,
apply(g, "1") is
argument 1: expected (String) -> Maybe<Int>, got (String, Bool) -> Maybe<Int>,
whose help suggests the capture &g(&1).
fn parse(s: String, strict: Bool = False) -> Maybe<Int> if strict then None else String.to_int(s) end fn main() f: (String) -> Maybe<Int> = parse dbg f("12") // Some(12) dbg Iter.map(["1", "x"], parse) |> Iter.to_list() // [Some(1), None] end
A fn declaration and a lambda bound to a name are two ways to name a
function, and one rule covers both. A function’s defaults, a lambda’s own
and a partial capture’s open defaults stay with the name and the local
names that copy it: after g = parse, g("12") fills strict, and so
does a copy of a copy, a pipe through it and a closure that captured it,
as h() does after h = fn x = 1 -> x. That holds for a module function,
an owner’s (p = Parser.parse) and a nested fn. A copy has no parameter
names: g(s: "12") is no parameter named 's'. A value passed on, taken
out of a container, bound with a type annotation or reached other than by a
local name has none, and a call through it that leaves an
argument out is expected 2 arguments, got 1, whose help is
a function type's parameters have no defaults; pass every argument. A
once that holds a lambda or a partial
capture has none either: after once ping = &connect(&1, port: &2),
ping("a") is expected 2 arguments, got 1.
Parameter types from defaults
Section titled “Parameter types from defaults”A parameter with a default may leave out its type when the default alone
tells it, by the rule for fields (§4 Field types from defaults): limit = 10 is an Int parameter, and mode = WriteMode.Replace a WriteMode.
This holds for a fn, a generic one included, a function in an impl
block or a type’s namespace, an interface’s default function, a host fn
and a lambda (§5 Lambda parameter types). A default that reads an
earlier parameter takes its type from it (fn window(page: Page, offset = page.size * 2)).
fn search(query: String, limit = 10, offset = 0) -> String "${query} ${limit} ${offset}" end fn main() dbg search("nomi") // "nomi 10 0" dbg search("nomi", offset: 20) // "nomi 10 20" end
A default whose type only an expected type tells is the field rule’s
error, can't tell this parameter's type from `None`, with
write `since: Maybe<_> = None`, with the type for each `_` . The
inferred type is the function’s signature for every caller, in every file,
and hover, signature help and the reference show it. A public function’s
parameter may not take a private type from its default
(function parameter exposes private type Secret).
Parameter Destructuring
Section titled “Parameter Destructuring”Taught in Functions & Lambdas.
A parameter of a function or lambda may be an irrefutable pattern instead of a name. The body sees the names it binds.
struct Point x: Int y: Int end fn sum(Point{x:, y:}) -> Int x + y end fn add_pair((a, b): (Int, Int)) -> Int a + b end fn main() dbg sum(Point{x: 1, y: 2}) // 3 dbg add_pair((3, 4)) // 7 end
A pattern whose head names a type gives the parameter that type, and needs
no annotation, though one is allowed: a distinct Duration(x), a named tuple
Pair(a, b), a named struct Point{x:, y:}, a single-variant enum’s
E.V(x). A pattern with no
type head needs one: a tuple, an anonymous struct pattern ({x:, y:}: Point),
a dot-leading variant (.V(x): E), and a generic distinct without type
arguments.
A head with nothing after it names the parameter’s type and binds nothing:
fn stats(Request) -> Response takes a Request, as _: Request does,
and so does a lambda’s fn Request -> .... The head may name any type
written as one name: a struct, an enum of any number of variants (the
parameter matches every value, whatever its variant), a distinct type, an
alias, a builtin such as String, or a type parameter. A generic type
needs its arguments, so fn f(Box) is the error that Box expects 1 type
argument, got 0.
The type alone may be written in any other form a parameter’s type takes,
and binds nothing the same way: a generic type, fn f(Vector<Int>, i: Int);
one named through its file, fn f(http.Request), fn f(mod.Box<Int>); a
tuple type, fn f((Int, String)); a function type, fn f((Int) -> Int);
an anonymous struct type, fn f({x: Int}). Where a pattern is spelled the
same, the pattern is read: Shape.Circle and geo.Shape.Circle are a
variant’s pattern, (a, b) a tuple pattern, and an annotation after the
parentheses or braces, (a, b): (Int, Int), makes them a pattern. A
lambda’s parameter takes these forms too, but not a function type alone:
in fn (Int) -> n the -> is the lambda’s, which takes an Int and
returns n, so a lambda takes a function it ignores as _: (Int) -> Int.
A name that is no type is unknown type "Label". A name that is also a
variant in scope is not read as a type: fn f(None) is
parameter 'None' needs a name, and a variant that a pattern may not write
bare, fn f(One), is the bare-variant error; where a type has the name too,
_: One takes the type and .One matches the variant. A call cannot name
such an argument, and an impl’s parameter matches an interface’s written so
whatever its name.
struct Request path: String end fn stats(Request) -> String "ok" end fn main() dbg stats(Request{path: "/"}) // "ok" end
The pattern must match every value of the parameter’s type. A refutable one
is refutable pattern in parameter; bind the parameter and use a `case` in the body:
a literal, a variant of an enum with more than one, a map or bracket
pattern (even one that matches every vector), and any
pattern holding one. A single-variant enum’s variant is irrefutable.
Duration(x) and Some(x) look alike; only the parameter’s type tells the
distinct from the variant.
Taught in Functions & Lambdas.
A call is a callee followed by arguments in parentheses. Only a function
value can be called: 1() is `Int` is not a function, and so is
calling a tuple, a list or a struct. How a callee is qualified is §8.
Named Arguments
Section titled “Named Arguments”An argument may name its parameter: connect(host: "x", port: 80). A
named argument whose value is a binding of the parameter’s name is punned,
as a struct’s field is: Response.json(body, status:) is
Response.json(body, status: status). Positional arguments come first. One positional argument may follow named
ones, and fills the first slot they left empty; two are
positional argument after named argument.
A call fills its parameters in this order:
- Positional arguments fill slots from the first, left to right, except a trailing callback (Lambdas at Call Sites).
- Named arguments fill their slots.
- Defaults fill the slots still empty.
- A slot without a default still empty is an error.
A named argument for a slot already filled, positionally or by an earlier
name, is parameter 'x' already has a value, at the later one.
A name needs a declaration to name. A declared fn, and a lambda or partial
capture bound to a name, have parameter names. A value whose type is only a
function type has none: a parameter or field of function type, a copy of a
function value, a call’s result, a value taken out of a container. A named
argument through such a value is no parameter named 'port', whose help is
a function type's parameters have no names; pass the arguments by position.
A variant’s
payload, a distinct’s wrapped value and a struct’s record call are
positional: Some(value: 1) is no parameter named 'value'. An
interface-qualified call takes the interface function’s own parameter names
(Display.to_string(value: 1), Struct.update(updates: {x: 2}, original: p)).
Lambdas at Call Sites
Section titled “Lambdas at Call Sites”Taught in Functions & Lambdas.
A lambda is passed inside the parentheses like any argument; there is no trailing-block syntax. When the callee’s last parameter is still empty, the final positional argument goes to that last slot, even past defaulted parameters between it and the earlier positional arguments. So a trailing callback stays unnamed when a middle default is skipped.
fn apply(x: Int, scale: Int = 1, f: (Int) -> Int) -> Int f(x * scale) end fn main() dbg apply(5, fn x -> x + 1) // 6 dbg apply(5, scale: 2, fn x -> x + 1) // 11 end
The parameter list decides the routing, not how the argument is written. A
lambda, a field accessor (Iter.sort_by(users, .age)) and a capture route
on sight. A bare name routes when the last parameter takes a function and
the slot it would otherwise fill does not; where both take functions, the
written order wins. A trailing positional after named arguments skips the
slots they claimed. A positional written before a named argument fills the
slot it sits in.
No Auto-Currying
Section titled “No Auto-Currying”A function is not curried: a call passes every argument, and a function of
some of them is a partial capture (&add(1, &1), Captures).
No Overloaded Functions
Section titled “No Overloaded Functions”A name in a scope has one definition. Nomi never picks among same-named
functions by argument type: use separate names (Date.parse, Time.parse),
or interfaces for polymorphism. Interface functions share a name across
types, but each call is qualified by a type or an interface (§8).
Lambdas
Section titled “Lambdas”Taught in Functions & Lambdas.
fn parameters -> body is a lambda. Its parameters are written as a
function’s are, without parentheses: names, annotations, defaults and
irrefutable patterns, separated by commas. A lambda with none writes nothing
between fn and ->. The first -> that is not inside a parameter’s
annotation ends the parameters, so fn f: (Int) -> Int -> f(1) takes f.
An annotation in parentheses is a function type when what follows its result
type ends a parameter (,, -> or =); otherwise the -> ends the
parameters, so fn p: (Int, Int) -> p.first takes a tuple p. A lambda that
takes one tuple apart writes the tuple pattern as its parameter,
fn (name, score) -> .... There is no implicit parameter.
fn main() double = fn x: Int -> x * 2 dbg double(4) // 8 dbg Iter.reduce([1, 2, 3], 0, fn total, x -> total + x) // 6 dbg Iter.map([("a", 1)], fn (_, n) -> n) |> Iter.to_list() // [1] dbg (fn -> 7)() // 7 end
A lambda takes the parameters of the function type its position expects
(§5 Assignability), so a lambda that ignores them still names each one
_. Where a (Request) -> ToResponse is expected, fn -> page is
this lambda takes no parameters, but a (Request) -> ToResponse takes 1 parameter,
whose help writes fn _ -> .... The one lambda of no parameters that stands
for a parameter is a stateless Iter.loop(fn -> ...) (§13 loop).
fn starts a declaration when a lowercase name and ( or < follow it;
anything else after fn starts a lambda. |x| x + 1 is not a lambda
(unexpected `|`).
A body on the ->’s line is one expression, and runs to the end of the
enclosing expression. A -> that ends its line takes the lines below as the
body, closed by end, and fn -> end is the empty body:
fn main() shout = fn s: String -> loud = String.uppercase(s) "${loud}!" end dbg [1, 2] |> Iter.map(fn n -> doubled = n * 2 doubled + 1 end) |> Iter.to_list() // [3, 5] dbg shout("hi") // "HI!" end
A block body’s result type comes from its last expression and its return
values, which must agree; a bare return gives Unit. A lambda parameter’s
default gives its type. A lambda parameter without an annotation or a
default takes its type from the expected function type (§5 Lambda
parameter types).
The body’s type is the lambda’s result, and an expected result that names
a type fixes what the body leaves open: against (Int) -> Result<Int, MyError>,
fn x -> Ok(x) is a Result<Int, MyError>. An expected result that is an
interface fixes nothing, so a type the body leaves open is Infallible, the
type with no values, since the body made no value of it. Passed as a
(Request) -> ToResponse, fn _ -> Ok(page) is a
Result<Response, Infallible> and fn _ -> Err(failure) a
Result<Infallible, Response>, and each implements the interface when
Infallible does. An Err(e) in the body names the error type, as it does
anywhere.
fn show(f: (Int) -> Display) -> String "${f(1)}" end fn main() dbg show(fn x -> Ok(x + 1)) // "Ok(2)" end
With no expected function type, the open type stays open, which is harmless
until something needs to know it: after f = fn x: Int -> Ok(x),
io.print(f(1)) is
Result<Int, _> needs Display (required by `where T: Display`), and nothing names the type its `_` stands for,
whose help writes the annotation, f: (Int) -> Result<Int, String> = fn x -> Ok(x).
Captures
Section titled “Captures”Taught in Functions & Lambdas.
A capture is a function written in place: & and the function’s body, in
which &1, &2, … stand for its parameters. The & stands against its
body, which is one of:
- a call:
&Int.max(&1, 0),&Some(&1 + 1),&f(&2, &1); - a parenthesized expression:
&(&1 > 2),&(&1 * 2 + 1),&(not &1); - a literal or construction:
&Point{x: &1, y: 0},&(&1, 0),&[&1, 0], and a string literal of any form, typed literals among them:&"id ${&1}"isfn x -> "id ${x}", and&Sql"id = ${&1}"isfn x -> Sql"id = ${x}".
fn main() dbg Iter.filter([1, 3], &(&1 > 2)) |> Iter.to_list() // [3] dbg Iter.map(["ab"], &String.length(&1)) |> Iter.to_list() // [2] add: (Int, Int) -> Int = &(&1 + &2) dbg add(1, 2) // 3 dbg Iter.map([7], &"id ${&1}") |> Iter.to_list() // ["id 7"] end
The body is one postfix-level operand, so &f(&1) + 1 adds 1 to a capture;
the function of the sum is &(f(&1) + 1). Anything else after & is
a capture is `&` and a call, a parenthesized expression or a literal, as in `&f(&1)` or `&(&1 > 2)` :
&x, &f(&1).x (write &(f(&1).x)), &Int.max (the function itself is
Int.max), &'a', &-1. ¬ f(&1) is the error that asks for
parentheses, and & (x) with a space is
a capture's `&` is written against its body, with no space: `&(&1 > 2)`, `&f(&1)`, `&Point{x: &1}` .
&N is parameter N of the capture around it. & and a decimal number from
1 with no leading zero is one token; &0 is
a capture's parameter is numbered from 1, with no leading zero: write `&1` for the first parameter, `&2` for the second.
Captures do not nest: &f(&1, &g(&1)) is
captures do not nest; write the inner one as `fn x -> ...` . A lambda
is a function of its own, so a capture inside a lambda inside a capture is
not nesting.
An &N outside every capture is
`&1` is a capture's parameter: write the function as `&(...)` or `&f(...)`,
whose help writes the capture it most likely belongs to
(Iter.map(xs, Int.max(&1, 0)) suggests &Int.max(&1, 0)). A capture with
no &N is a capture uses at least `&1` , whose help writes fn -> f().
_ is not a parameter: as an argument, add(1, _) is
`_` is a discard name, not a value, whose help writes &add(1, &1);
in a pipe stage, |> add(100, _), the help writes |> then &add(100, &1).
Parameters and their types
Section titled “Parameters and their types”The function type a capture’s position expects fixes its parameter count
and types, as for an unannotated lambda. Each &N must name one of them:
Iter.map(xs, &(&2 + 1)) is
`Iter.map` passes one argument; `&2` names a second, and against an
annotation, the function expected here takes one argument; `&3` names a third.
A parameter no &N names is ignored, one &N may stand several times
(&(&1 * &1)), and in any order. With no function type expected,
f = &(&1 > 2) is cannot infer type for `&1` in `&(&1 > 2)` .
Some(&(&1 + 1)) is a Maybe holding a function; &Some(&1 + 1) is a
function returning a Maybe.
A partial capture needs no expected type. It is a capture whose body is
a call taking each &N as one of its own arguments, positional or named,
numbered in the order written, each once (&add(1, &1),
&connect(&1, port: &2)). It is a partial application: its parameters are
the callee’s at those slots, with their types, names and defaults, and it is
held to the callee’s argument count (&add(&1, 1, 2) is
expected 2 arguments, got 3). A generic callee is solved from the expected
function type when there is one. An expected function type with more
parameters gives the extra ones, which it ignores. A call whose &Ns repeat,
come out of order or stand deeper than its own arguments is not a partial.
fn connect(host: String, port: Int = 8080, timeout: Int = 30) -> String "${host}:${port}/${timeout}" end fn main() c = &connect(&1, port: &2) dbg c(port: 80, host: "x") // "x:80/30" dbg c("y") // "y:8080/30" end
A partial of an operator’s function (&Int.divide(12, &1)) takes each open
operand’s type from the expected function type, which picks among the type’s
impls. With nothing expected, an open left operand is the type that
qualifies the function (f = &Int.divide(&1, 2) takes an Int, and f(9)
is 4), and an open right operand is the right-hand type of the type’s one
impl (&Int.divide(12, &1) takes a NonZeroInt); with several it is
cannot infer type for `&1` in `&Date.add(day, &1)` , whose help names
the impls.
Any other capture’s parameters have no names and no defaults, except a
struct literal whose &Ns are its whole fields, each once, which takes the
fields’ names: after mk: (Int) -> Point = &Point{x: &1, y: 0}, mk(x: 3)
works, while big(lhs: 3) after big: (Int) -> Bool = &(&1 > 2) is
no parameter named 'lhs'.
Evaluation
Section titled “Evaluation”A capture is a function value: nothing in its body runs when it is made,
and a call evaluates the whole body, as the equivalent lambda does.
&(&1 > limit()) calls limit on every call. A partial capture’s written
arguments run in its call’s order. A capture routes to a trailing callback as
a lambda does, and it carries no starting value: Iter.reduce(xs, &(&1 + &2))
is expected 3 arguments, got 2.
In &(&1 > 2) and ready, nothing expects a function of the capture; the
function of the whole condition is &(&1 > 2 and ready).
Closures
Section titled “Closures”Taught in Functions & Lambdas.
A lambda, a nested fn and a task’s body are closures. A closure copies the
value of each name it reads when it is made, and reads those copies from
then on. A later binding of the same name, a same-scope shadow included, is
a new binding that does not reach it.
fn make_greeter(greeting: String) -> (String) -> String fn name -> "${greeting}, ${name}!" end fn main() x = 1 f = fn -> x x = 2 dbg f() // 1 dbg x // 2 dbg make_greeter("Hello")("Ada") // "Hello, Ada!" end
A nested fn that calls itself refers to itself through its own closure.
Function values
Section titled “Function values”A named function, referred to without a call, is a function value: it can be
bound, passed and returned (Iter.map(users, format_user)).
A generic function used as a value is instantiated against the function type
its position expects, and its where bounds are checked at those types:
Iter.each(names, io.print) passes io.print at (String) -> Unit. A
position that leaves a type parameter unsolved, as f = ident does, is
cannot infer type parameter T of generic function 'ident' used as a value: nothing here gives it a function type; annotate one (`f: (Int) -> Int = ident`) or pass it where a function type is expected.
Constructors as Function Values
Section titled “Constructors as Function Values”Taught in Structs, Enums & Distinct Types.
A positional variant named without a call is its constructor:
Shape.Circle is a (Float) -> Shape, and Some a (T) -> Maybe<T>. So is
a distinct type that wraps a value: Id for type Id Int is an
(Int) -> Id. A value built through the function equals the one the call
builds.
enum Shape Circle Float Segment (Int, Int) end fn main() dbg Iter.map([1.0], Shape.Circle) |> Iter.to_list() // [Circle(1.0)] dbg Iter.map([(1, 2)], Shape.Segment) |> Iter.to_list() // [Segment(1, 2)] somes: List<Maybe<Int>> = Iter.map([1, 2], Some) |> Iter.to_list() dbg somes // [Some(1), Some(2)] end
- A generic constructor is instantiated as a generic function value is.
OkandErrleave the other type parameter to the result, soIter.map(ns, Ok)needs an annotated destination. With nothing to solve it from,f = Someiscannot infer type parameter T of generic constructor 'Some' used as a value: .... - A variant over a tuple takes the tuple:
Shape.Segmentis a((Int, Int)) -> Shape. Its flat call is a call form of the one tuple, and a partial capture leaves one element open (&Shape.Segment(&1, 0)is an(Int) -> Shape). A distinct over a tuple is the same:Pairis a((Int, String)) -> Pair, andPair(1, "x")builds one from the elements. - A bare variant is a value, not a function:
Shape.Pointis aShape. - A struct and a struct-shaped variant are not function values:
f = Shape.RectangleisShape.Rectangle is a struct-shaped variant and is not a function value; .... A lambda that builds one is the function. .Variantis not a function value, since a function type is not an enum:f: (Float) -> Shape = .Circleis an error whose help namesShape.Circle.- An opaque type’s constructor is private outside its file, as a value too.
Field Accessors
Section titled “Field Accessors”Taught in Structs, Enums & Distinct Types.
.name is a function that reads field name from its argument. A chain
.address.city reads one field after another, and an ordinal reads a
tuple’s item (.first, .second.first, §4 Tuples). A lowercase name
after the dot is a field; a capitalized one is a .Variant.
struct User name: String age: Int end fn main() users = [User{name: "Ada", age: 36}, User{name: "Alan", age: 41}] dbg users |> Iter.map(.name) |> Iter.to_list() // ["Ada", "Alan"] age: (User) -> Int = .age dbg Iter.map(users, age) |> Iter.to_list() // [36, 41] end
An accessor stands only where a function type (S) -> R of one parameter is
expected, and S must be known at its position: an annotation, a declared
parameter type, or a generic parameter an earlier argument or the piped value
has pinned. S must be a struct, an anonymous struct or a tuple. The
accessor is (S) -> F, F the last field’s type, and R unifies with F.
A generic struct is read at its instance, and a field holding a function is
returned, not called. As an argument, an accessor routes like a trailing
lambda.
The errors, each at the accessor:
- No function expected:
`.name` reads a field only where a function is expected; write `x.name` to read it from a value. As a pipe stage:`.name` is not a pipe stage; read the field from the value instead, as in `x.name`. - The parameter type is not known yet, as in
apply(.name, user)where a later argument would give it:`.name` needs the record type it reads from; annotate the binding, e.g. `f: (User) -> String = .name`. - No such field:
struct 'User' has no field 'nmae', with the helpdid you mean 'name'?. - Not a record:
`.name` reads a field of a struct, a record or a tuple, and Int is none of those.
Returning
Section titled “Returning”A function’s result is its body’s last expression. return value leaves
the nearest function or lambda with value, and a bare return leaves a
Unit one. return, break and continue leave only the function they are
written in; there is no non-local exit and there are no exceptions (§13). A
? inside a lambda returns from the lambda (§11). A return inside a nested
function, a lambda or a concurrent block belongs to that inner boundary.
A tail return value is legal.
A bare return the body would reach its end without is an error: one that
is the last statement of a function, lambda or test body, reached through
the last statement of a block, a branch of a final if or an arm of a final
case (this `return` does nothing: it is the last statement of `reset` ),
and a final if or case whose every branch is empty or a bare return
(this `if` does nothing: every branch returns and nothing follows it). A
bare return after a dbg statement is not one: it discards that
statement’s value.
A statement after one that always exits can never run, and is an error at that statement whose help is “remove it”. A statement always exits when it is:
- a
return,breakorcontinue(unreachable code after return); - an
unreachable(unreachable code after `unreachable`, §11); - an
ifwith anelsewhose every branch exits (unreachable code: the `if` above returns in every branch); - a
casewhose every arm exits (unreachable code: the `case` above returns in every arm); - a block that holds one (
unreachable code: the block above always returns); - an
Iter.loopstatement whose callback holds nobreakof its own (unreachable code after a loop that never breaks, with the help “remove it, or give the loop abreakthat ends it”; §13).
A todo is Unit and does not exit, so code after a stub stays legal, and
no other call counts as an exit. When the branches of an if or case all
exit and one of them traps, the message says it exits in every branch; when
all of them trap, it says it traps.
Tail-call optimization
Section titled “Tail-call optimization”A call in tail position runs in constant stack space: it replaces the
caller’s frame instead of adding one. This is a guarantee, with no
annotation and no recur form, for every tail call to a Nomi function:
direct, mutual, through a function value and through interface dispatch. A
host function has no frame to replace.
A call is in tail position when its value becomes the enclosing function’s result with nothing done after it. Tail position reaches:
- the last expression of a function or lambda body, and the last statement of a block in tail position;
- both branches of an
if, and every arm of acase(not a guard), in tail position; - the last stage of a pipe in tail position;
- the operand of
return; - the right operand of
andandor.
It does not reach:
- into a lambda, which has its own tail position: in
Iter.reduce(xs, 0, fn acc, x -> f(x)), the call tofis the lambda’s tail, not the outer function’s; - a default expression, which runs before the body;
- the operand of
?, whose result is matched before it returns.
A nested fn is a function, with its own tail position.
A call in tail position while a defer registered in a block around it is
pending is an ordinary call, since the deferred call runs after it returns:
fn leave(n: Int) dbg n end fn down(n: Int) -> Int defer leave(n) if n == 0 then 0 else down(n - 1) end fn main() dbg down(1) // 0 end
leave(0) runs before leave(1), and each down keeps its frame until its
deferred call has run. A defer in a block that has already ended is not
pending. Recursion that registers a defer at each step keeps a frame per
step, and counts toward the limit of Recursion depth.
A trap inside tail-recursive code reports one frame, however deep the iteration ran.
Recursion depth
Section titled “Recursion depth”At most 100,000 calls may be in progress at once on one task. The call that would start one more is a trap at its line:
line 4: stack overflow: more than 100000 nested calls
It is a trap like any other (§11). Each spawned task counts from zero. A tail call keeps no frame and does not count, so a tail-recursive loop that never reaches its base case runs forever.
A function that cannot return without calling itself with the arguments it
was given is a compile error at its name: every path through its body
reaches a call by its own name, its owner (Foo.again(foo)) or, in an impl,
its interface (Display.to_string(value)), passing each parameter, or a
plain binding of it, in its own position or by its own name. A call outside
tail position always counts. A call in tail position counts only when
nothing before it on its path calls a function, since an effect there can
make the loop deliberate (a fn serve(l: Listener) whose body is
handle(l); serve(l)).
fn grow(x: Int) -> Int y = grow(x) // error at `grow` above y + 1 end
The error is
every path through grow calls grow(x) with the arguments it was given, so it never returns.
A path that returns without the call, a call with an argument changed, a
call inside a lambda, mutual recursion and interface default bodies are not
checked.
Exported Functions
Section titled “Exported Functions”Taught in Building & Shipping.
export fn declares a top-level function that a host calls by name: a web
page, or a WASI runtime. Its arguments and result cross as JSON, through
FromJson and ToJson. How a host calls one is in the tooling
reference.
import std::json.{FromJson, ToJson} struct Game word: String guesses: List<String> end derive ToJson for Game derive FromJson for Game export fn new_game(word: String) -> Game Game{word:, guesses: []} end export fn guess(game: Game, letter: String) -> Game {..game, guesses: [letter, ..]} end
- Top level only.
exportis the only modifier and comes first. Before anything butfnit is`export` marks a function: `export fn name(...)`. Inside a body it is`export` applies to top-level functions only, and in animplblocka function in an `impl Type` block cannot be exported: `export fn` declares a top-level function. Ahost fnand agobinding have no body to export (a `host fn` is supplied by the host and cannot be exported; an `export fn` has a body). - Not
pub.pubmakes a function visible to the program’s other files;exportmakes it callable from outside the program.pub export fnisan exported function takes no `pub`: write `export fn`. An exported function is not a member of its file, so other files cannot call it:other.twice(2)for anexport fn twicein other.nomi isfile 'other' has no member 'twice'. Other files call the plain function an exported one wraps. - Concrete. An exported function is not generic
(
exported function `ident` cannot be generic: a host calls it with JSON values of one known type), and each parameter and the result is one known type, not an interface value. - JSON. Each parameter’s type implements
FromJsonand the result’sToJson, type arguments included. AUnitresult crosses as nothing. A violation names the parameter, the type and the interface:parameter `p` of exported function `sum` cannot cross as JSON: `Plain` does not implement `FromJson`, with help naming the derive. - One name. No two files of a program export one name:
exported function `guess` is already exported by other.nomi: a host calls exported functions by name, so each name is exported once, at the second, with the first as a related location. - Effects. An exported function may do anything a function may.
A program with exported functions needs no fn main. Exported functions are
checked and lowered whether or not main reaches them. Running such a
program with no main is an error that says to build it for a host
(tooling reference).
Values cross as ToJson writes them and FromJson reads them:
| Nomi | JSON | JavaScript |
|---|---|---|
Int | number, its exact digits at any size | number, or a BigInt past Number.MAX_SAFE_INTEGER |
Float | number | number |
String, Bool | string, boolean | string, boolean |
Decimal | string of its exact digits, scale kept ("12.50"); a number is read too | string |
Uuid | string, lowercase 8-4-4-4-12 hex | string |
Instant | string, RFC 3339 in UTC ("2023-11-14T22:13:20.25Z"); any offset is read | string |
Date, Time, NaiveDateTime | string, YYYY-MM-DD, HH:MM:SS[.fff], YYYY-MM-DDTHH:MM:SS[.fff]; a year outside 0000 to 9999 as +010000 | string |
List<T>, Vector<T>, Set<T> | array | array |
Map<String, V> | object | object |
| struct | object, as derive ToJson writes it | object |
| enum | a bare variant’s name as a string; {"Variant": payload} for one with a payload | string or object |
Maybe<T> | the value, or null for None | the value or null |
Unit (a result only) | nothing | undefined |
A Float parameter reads a whole number too, since JavaScript writes 2.0
as 2. An Int crosses exactly in both directions: the loaders read an
integer past Number.MAX_SAFE_INTEGER from its own digits as a BigInt, and
write a BigInt argument as its digits, so 9007199254740993 arrives as
9007199254740993n rather than rounded to 9007199254740992.