Bindings & Expressions
A Nomi program is a list of declarations, and it starts running at
fn main. This chapter covers the pieces you’ll use in almost every file:
values, bindings, blocks, and if and case.
A first program
Section titled “A first program”fn main()
greeting = "Hello, Nomi!"
dbg greeting
enddbg line 3: greeting = "Hello, Nomi!"
dbg prints the line it is on, the expression, and the value. Then it
returns the value unchanged, so you can put it in the middle of an
expression. It works on every value, and the tour uses it throughout. It is
for looking while you work: nomi build refuses a program that still has a
dbg.
To print output for the people using your program, use
std::io:
import std::io
fn main()
io.print("Hello, Nomi!")
io.inspect("Hello, Nomi!")
endHello, Nomi!
"Hello, Nomi!"
io.print prints a value the way a user should see
it. A string prints without quotes. It works for strings, numbers, booleans,
and any type that implements Display, which
Interfaces & Dispatch covers.
io.inspect prints any value in its debug form,
which is why the string has quotes. When you define your own types later,
io.inspect can print them with no extra work.
io.inspect returns Unit, the value an expression
gives when it has nothing useful to return. So use io.inspect as a
statement on its own line. Use dbg when you want to look at a value and
keep using it.
Nomi code has one layout, which nomi fmt writes and editors apply when you
save; the examples here format themselves after each edit
(Formatting).
Tiny functions
Section titled “Tiny functions”fn double(n: Int) -> Int
n * 2
end
fn main()
dbg double(4)
enddbg line 6: double(4) = 8
A function is written fn name(params) -> ReturnType, its body on the
lines below, and end. The last expression in the body is the value the
function returns. Every body in Nomi is written this way: a header line, the
lines below it, and end.
That is enough for the examples in this chapter. Functions & Lambdas covers the rest: default values, lambdas, callbacks, and parameters that unpack their arguments.
Comments and tiny tests
Section titled “Comments and tiny tests”Nomi keeps comments, documentation and tests next to the code they describe.
//# Geometry helpers.
/// Returns the area of a rectangle.
fn area(width: Int, height: Int) -> Int
// Rectangles multiply their sides.
width * height
end
fn main()
dbg area(6, 7)
enddbg line 10: area(6, 7) = 42
There are three kinds of comment:
//is an ordinary comment.//#documents the whole file.///documents the declaration below it. Editors show it on hover, and the generated reference pages are built from it.
A test can live in the same file as the code it checks:
fn double(n: Int) -> Int
n * 2
end
test "double doubles its input"
assert double(4) == 8
refute double(4) == 9
endok double doubles its input
test result: ok. 1 passed, 0 failed
assert fails the test when its condition is false. refute fails it when
its condition is true.
For a small example, write it directly above the declaration with //!:
//! assert double(4) == 8
//! refute double(4) == 9
fn double(n: Int) -> Int
n * 2
endok double //! test lines 1-2
test result: ok. 1 passed, 0 failed
nomi test runs these as tests. Editors treat them as code, with hovers and
errors. The standard library uses them for its examples: the reference
entry for
String.contains is
generated from them.
assert and refute are for tests. Testing covers the rest.
Bindings
Section titled “Bindings”fn main()
name = "Nomi"
port = 8080
dbg name
dbg port
enddbg line 4: name = "Nomi"
dbg line 5: port = 8080
name = expression gives a name to a value. There is no let. A binding
never changes: the name stands for that one value.
The = does not assign to a variable. It matches the value on the right
against the name or pattern on the left. Later chapters use patterns there
to unpack values.
Nomi works out a binding’s type from the expression on the right. Type annotations below shows when you need to write the type yourself.
Every binding must be read. If you mean to ignore a value, bind it to _
or to a name that starts with _, such as _unused_port:
fn main()
_ignored_count = 3
dbg "done"
enddbg line 3: "done" = "done"
The same rule applies to an expression on a line by itself. Before the last
line of a block, such an expression must return Unit, as io.print(...)
does. If it returns a value, use the value, look at it with dbg, or
discard it with _ =:
fn compute() -> Int
42
end
fn main()
_ = compute()
dbg compute()
Unit
enddbg line 7: compute() = 42
This version is an error, because nothing uses the Int that compute()
returns:
fn compute() -> Int
42
end
fn main()
compute()
Unit
endmain.nomi:6:5: non-final expression has type Int, but only Unit results can be ignored — write `_ = ...` if intentional, use `dbg ...` to inspect it, or move it to the end to return it
Moving compute() to the last line doesn’t help here. It would become
main’s result, and main can only return Unit or Result<Unit, E>.
You can bind a name that is already in use. The new binding shadows the old one: from that line on, the name means the new value. Nothing is mutated. Functions and types at the top of a file can’t be redeclared this way.
Shadowing is useful when you refine a value one step at a time:
fn main()
name = " JANE "
name = String.trim(name)
name = String.lowercase(name)
dbg name
enddbg line 5: name = "jane"
Each line reads the previous name and binds a new one. When each step
feeds straight into the next, a pipeline says the same thing more simply.
The pipe operator |> passes each stage’s result to the stage below it, and
Pipes covers it in detail:
fn main()
" JANE "
|> String.trim()
|> String.lowercase()
|> dbg
enddbg line 5:
" JANE "
|> String.trim()
|> String.lowercase()
= "jane"
A bare dbg can end a pipeline like this, or sit between two stages.
A binding that is replaced before anything reads it is an error. In
name = "Jane" followed by name = "John", the compiler reports that the
first name is never read.
Fine print
- A shadowing binding may have a different type from the one it hides. A lambda made before the shadow keeps the value it captured.
_can’t be read back: using it as a value is an error. A name that starts with two underscores, such as__x, is an ordinary binding.- The read rule covers every name a pattern binds: a destructured
parameter, a
casearm, anifcondition. - Two statements need a newline, a space or
;between them.
fn main() name = "a" read_name = fn -> name name = 3 dbg read_name() // "a" dbg name // 3 end
Type annotations
Section titled “Type annotations”Most bindings don’t need a type written out, because Nomi reads it from the right-hand side. You need one when the right-hand side doesn’t say what the type is. The usual case is an empty collection:
fn main()
// The annotation says what the map holds.
scores: Map<String, Int> = {}
Map.size(scores) |> dbg
// A call can take the types instead.
Iter.to_map<String, Int>([])
|> Map.size()
|> dbg
enddbg line 4: Map.size(scores) = 0
dbg line 9:
Iter.to_map<String, Int>([])
|> Map.size()
= 0
{} alone could be a map of any key and value types, and [] could be an
empty list, vector or set of anything, so each needs its type from
somewhere. There are three ways to give one:
- Annotate the binding:
scores: Map<String, Int> = {}. Use this when you name the value. - Give type arguments to a call:
Iter.to_map<String, Int>([]). Use this when the value goes straight into a pipe or another call.Iter.to_mapbuilds a map from pairs; Collections covers it. - Write
asafter the value:{name: "Ada", tags: [] as List<String>}. Use this where no annotation fits, such as a field of an anonymous struct.asonly states the type; it never converts a value.
Without one of these, the compiler reports that the binding’s type is not locally determined.
Fine print
- A binding is refused only when its type is wholly unknown:
xs = [],x = None,ch = Channel.buffered(4).x = Ok(42)is accepted as aResult<Int, E>whose error type is fixed later. - A destructuring binding is refused when a name it binds still has a
wholly unknown type once the file is checked:
(a, b) = (None, 1)is an error unless a later use ofafixes its type. - Type arguments work on any call, constructors included:
Some<Int>(42),Channel.buffered<Int>(4). - A lambda bound with no annotation,
f = fn x -> x, iscannot infer type for parameter x. Annotate the parameter (fn x: Int -> x) or the binding (f: (Int) -> Int = ...).
Spec: Locally-determined bindings and turbofish, Lambda parameter types.
Blocks are expressions
Section titled “Blocks are expressions”fn main()
total = begin
a = 10
b = 20
a + b
end
dbg total
enddbg line 8: total = 30
A begin … end block runs its lines and gives the value of its last
expression. Names bound inside the block, like a and b, are not visible
outside it. That makes a block a tidy place for intermediate steps.
Fine print
- A block whose last statement is a binding has the value
Unit. - An expression before the last line must be
Unit, except adbg. A function that returnsUnitmay end withdbg expror|> dbg. ;ends a statement, so two short statements fit on one line:a = 1; a + 1.- A line that starts with
|>,and,or,is,inor a comparison continues the line above. A line that starts with+or-does not, so a long sum breaks after its operator.
Spec: Block expressions, Statements and the Unit rule, Statement ends.
if/else and case are expressions
Section titled “if/else and case are expressions”if/else and case also give values, so you can bind their result:
fn main()
x = 42
size = if x > 50 then "big" else "small"
dbg size
label = case x
0 -> "zero"
1 -> "one"
_ -> "many"
end
dbg label
range = case
x < 0 -> "negative"
x < 10 -> "small"
x < 100 -> "medium"
_ -> "large"
end
dbg range
enddbg line 5: size = "small"
dbg line 13: label = "many"
dbg line 22: range = "medium"
iftakes aBoolcondition. With more afterthenon its line it is one line, assizeis. Athenthat ends its line takes the lines below, up toelseorend, as a function’s body does.- An
ifwithoutelseis a statement: its branch isUnit, such as a print, or leaves withreturn. A branch with a value needs anelse, and a value that may be absent is aMaybewithNoneas itselse:if x > 50 then Some("big") else None. case x…endcomparesxagainst each pattern in turn and uses the first arm that matches._matches anything. An arm whose->ends its line takes the lines below as its body, up to the next arm.case…end, with nothing aftercase, takes the first arm whose condition is true. Use it instead of a longelse ifchain.
Pattern Matching covers patterns in full, including
the if Pattern = expr form.
File-level values with once
Section titled “File-level values with once”once max_retries = 3
once timeout_ms = 30 * 1000
fn main()
dbg max_retries
dbg timeout_ms
enddbg line 5: max_retries = 3
dbg line 6: timeout_ms = 30000
once declares a value at the top level of a file. Its expression runs the
first time the value is used, and later uses get the saved result. Use it
for constants and configuration.
Fine print
- The initializer runs once even when several tasks read the value at the same time.
- An initializer is not a function body, so
?,return,breakandcontinuewritten directly in it are errors. A lambda inside it is a body of its own. - A
oncewhose initializer reads itself, directly or through the functions it calls, is a compile error naming the chain. A cycle through a function value or an interface value traps when it runs instead:cyclic 'once' binding: 'a' depends on itself. - A
oncemay also stand in an inherentimplblock and is read through its type:Money.zero.
struct Money cents: Int end impl Money pub once zero = Money{cents: 0} end
Spec: once Bindings.
How far type inference reaches
Section titled “How far type inference reaches”Inside a function body, Nomi works out types from how values are used:
- In
Iter.map(xs, fn x -> x + 1), the type ofxs’s elements and the type of the lambda’sxare worked out together. Ok(42)is aResult<Int, E>whose error typeEis not known yet. Something nearby fixes it: a binding’s annotation, the function’s return type, or anothercasearm.- In
f: (Int) -> Int = fn x -> x + 1, the lambda’sxgets its type from the annotation, so you don’t writefn x: Int ->.
Inference stops at two boundaries.
Function signatures are written out. Every fn writes its parameter
types, and its return type unless it returns Unit. A parameter with a
default may leave its type to the default, as in limit = 10. Leaving the
return type off means the function returns Unit. Nomi never works out a
signature from the body.
This keeps a function’s types visible where it is declared. Readers, reviewers and editors see them without tracing other code. If you change a function’s body, its signature stays the same, so callers keep working or the error appears in the function you changed rather than in some caller.
Each binding’s type is settled where it is written. The type has to come from an annotation on the binding, or from the expression on the right and what is expected of it there. Later lines don’t count:
fn main()
m = {} // error: nothing here says what the map holds
m = Map.put(m, "alice", 90)
dbg m
endmain.nomi:2:5: binding 'm' type is not locally determined: it has unsolved type parameter(s) — add an annotation (`m: T = …`) or a type argument (`f<T>(…)`)
The second line would tell the compiler that m maps String to Int.
Nomi rejects the first line anyway, so that someone reading from the top
knows what m is without looking ahead. The fix is an annotation or a type
argument, as in Type annotations.
Most lines in a function body need no annotation. You write types at signatures, and on the few bindings whose type the line itself doesn’t show.
See it in action
Section titled “See it in action”Every example that uses Bindings & Expressions
Functions & Lambdas is next.