Skip to content

8. Expressions

Expressions, patterns and types nest at most 256 levels deep. Blocks, parentheses, list, vector, set, map, tuple and struct literals, lambdas, if bodies, unary operators, interpolations and type arguments each add a level. A chain of binary operators, |> stages or else if arms does not. Deeper nesting is a parse error at the first token past the limit: nesting deeper than 256 levels; move the inner part into a binding or a function.

Operands and arguments are evaluated once each, left to right as written. A named argument is evaluated where it is written, not where its parameter stands, so f(b: g(), a: h()) runs g before h. A pipe’s head is evaluated before the stage’s other arguments. x in c evaluates x before c. and and or evaluate their right operand only when the left does not decide the return (Logical operators).

fn add(a: Int, b: Int) -> Int
    a + b
end

fn main()
    _ = add(b: dbg 1, a: dbg 2) // prints 1, then 2
    _ = (dbg 3) |> add(dbg 4)   // prints 3, then 4
end

The operator set is fixed. A program cannot define an operator or change a precedence. The arithmetic operators +, -, *, / and % and the bitwise operators dispatch through std interfaces (Operators through interfaces).

Precedence, from loosest to tightest:

LevelOperators
1or
2and
3prefix not
4== != is in
5< > <= >=
6|> as
7.. ..=
8+ - ||| ^^^
9* / % &&& <<< >>>
10prefix - ~~~
11calls, field access, postfix ? and !
  • Binary operators of one level associate to the left.
  • The bitwise levels are Go’s: x &&& mask == 0 is (x &&& mask) == 0, and hi <<< 8 ||| lo is (hi <<< 8) ||| lo.
  • is and in bind as == does but do not associate. Neither chains with ==, !=, an ordering operator, is or in (Pattern test: is, Membership: Contains).
  • Prefix not takes everything to its right that binds at least as tightly as == (Logical operators).
  • as takes a type, not an expression, on its right, and ascribes everything to its left at its level, so xs |> Iter.to_list() as List<Int> ascribes the pipeline and a == b as T is a == (b as T). It does not chain (§5 Type ascription).

Other operator tokens: ? and ! (postfix, §11 Propagating with ?, §11 Unwrapping with !), = (binding, §6), . (field access and qualification, Field access), and & (capture, §7 Captures).

Taught in Scalars and Strings.

+, -, *, / and %, and prefix -.

  • Int, Float and Decimal have +, -, *, /, % and prefix - over two operands of one type. % is the remainder of /’s truncating division and takes the sign of the left operand (Integer division and remainder).

  • The numeric types never mix. 1 + 2.0, 1 + 1.50d, 1 < 2.0 and 1 == 1.0 are compile errors (`+` needs two values of one type, and these are Int and Float, equality type mismatch: Int vs Float, comparison type mismatch: Int vs Decimal). Convert with Int.to_float, Float.to_int, Int.to_decimal, Decimal.to_float or Float.to_decimal.

  • An operand of a subtype is its base’s value, and the result is the base’s, except that +, * and prefix - on the std numeric subtypes keep one where it provably holds: with count a NonNegativeInt, count + 1 is a PositiveInt and count - 1 an Int (§4 Arithmetic on numeric subtypes).

  • + on two String or two Bytes values concatenates.

  • On collections, + and - combine two collections of one type. List<T> + List<T> and Vector<T> + Vector<T> concatenate. Set<T> + Set<T> is the union and Set<T> - Set<T> the difference. Map<K, V> + Map<K, V> is Map.merge: on a shared key the right-hand value wins. Map has no -. There is no collection-plus-element form: write s + Set[x], list + [x] or m + {k => v}.

  • A collection literal operand beside an operand of the same collection is built as that operand’s type, on either side, as a literal is under an annotation (§5 Covariant conversion): with routes: List<(Route, Handler)>, [(Route`GET /`, home)] + routes is a List<(Route, Handler)> though home is a (Request) -> Response. Two operands that each have a type of their own must have one type: with mine = [(Route`GET /`, home)], mine + routes is the error that + needs two values of one type.

An Int holds a whole number of any size. +, -, *, prefix -, / and % give exact results and never overflow. A value that fits in 64 bits costs what a machine integer costs; a larger one grows as it needs to.

fn main()
    dbg 9_223_372_036_854_775_807 + 1                  // 9223372036854775808
    dbg -(-9_223_372_036_854_775_808)                  // 9223372036854775808
    dbg Int.wrapping_add(9_223_372_036_854_775_807, 1) // -9223372036854775808
end

Int.wrapping_add, Int.wrapping_sub and Int.wrapping_mul return the low 64 bits of the exact result as a signed 64-bit Int, for arithmetic defined over 64 bits (a hash, a checksum). derive Hashable mixes with them.

Where a value must fit a machine integer, the boundary says so:

  • An index, a count or a size past 64 bits reads as past any collection: Iter.get(xs, Int.pow(10, 30)) is None, Iter.take(xs, Int.pow(10, 30)) takes all of xs, and Vector.get(v, Int.pow(10, 30))! traps as any index out of range does.
  • A Go function bound with go (§19) that takes int64, int or a narrower integer declares a parameter type whose every value it holds: Int64, or a subtype whose rule bounds it within the Go type’s range. A plain Int there is an error at the binding (§19 How Nomi types project to Go), so Int64.try_from(n) checks a computed value before the call. A Go uint64 result past 64 signed bits is an exact Int. A Go *big.Int parameter or result takes any Int, and a nil *big.Int result traps (`pkg.F` returned a nil *big.Int, which is not an Int).
  • A library type with a 64-bit range says so in its reference: a database driver refuses an Int its engine cannot store. A Duration is an Int of nanoseconds with no range, and an Instant an Int of nanoseconds from the epoch with none, so Instant + Duration never faults; a wait past the 64 bits the clock counts (about 292 years) never ends, and a deadline past 2262 never comes. The calendar types have no range either: a Date’s year is an Int of any size, an OffsetDateTime or DateTime holds any Instant, and no construction, conversion or arithmetic on them faults for how far it goes. A year outside 0000 to 9999 is written in ISO 8601’s expanded form, a sign and at least six digits (+010000-01-01, -000001-12-31), and every parse reads it back. std::json reads and writes an Int of any size, and an export fn result past ±2⁵³ fails the call (§7 Exported Functions).

/ truncates toward zero. % is the remainder of that division and takes the sign of the dividend, so (a / b) * b + (a % b) == a: -7 / 3 == -2 and -7 % 3 == -1.

  • The divisor is a NonZeroInt: std’s impls are Divide<NonZeroInt, Int> and Remainder<NonZeroInt, Int>, and Int.divide and Int.remainder take one. A divisor passes when it is a non-zero literal, when its type is NonZeroInt or below it, or when its range proves it off zero (§4 Value ranges): a binding checked first (§4 Narrowing), n + 1 with n a NonNegativeInt, Duration.minutes(15). Any other divisor is an error at the divisor that says how to make it one: `/` divides by a NonZeroInt; `elapsed` is an Int with the help check it first (`if elapsed == 0 then ...`) or take a NonZeroInt. A divisor that is always zero is division by zero: the divisor is the literal 0, or with zero = 0, division by zero: `zero` is 0 here.
fn per_hour(count: Int, hours: Int) -> Int
    if hours == 0 then return 0
    count / hours // hours is a NonZeroInt here
end

fn average(total: Int, n: PositiveInt) -> Int
    total / n
end

fn main()
    dbg per_hour(120, 4)                             // 30
    dbg average(10, 4)                               // 2
    dbg 7 % 3                                        // 1
    dbg Int.divide(9, NonZeroInt.try_from(3 - 1)!) // 4
end
  • So a checked program never divides an Int by zero. The VM still checks each division and stops with line N: division by zero (§11 Traps, Maybe and Result), a backstop no checked program reaches.
  • A generic function that divides by its own type, where T: Divide<T, T>, does not take an Int, whose / takes a NonZeroInt; one bounded by the divisor’s type does: fn rem<T, D>(a: T, b: D) -> T where T: Remainder<D, T> takes rem(10, NonZeroInt(4)).
  • The named functions that divide take a non-zero divisor too: Int.modulo(x, y) and Int.floor_div(x, y) a NonZeroInt, and Decimal.divide and Decimal.divide_exact a NonZeroDecimal, so Int.modulo(x, 0) is 0 is not a NonZeroInt: `fn n -> n != 0` is false.
  • An impl of Divide or Remainder for a type of one’s own takes a divisor that cannot be zero in the same way: a NonZeroInt (impl Divide<NonZeroInt, Score> for Score, so score / 4), or a subtype of its own type whose rule rules zero out (impl Divide<NonZeroRational, Rational> for Rational). Its body divides an Int under the same rule as any other code.
  • Float’s % is IEEE 754’s fmod: a - b * trunc(a / b) computed exactly, with the sign of a (-7.5 % 2.0 == -1.5). It never traps: a zero divisor or an infinite dividend gives NaN, and an infinite divisor gives a.

Floored division and modulo, powers, roots and digits are functions in std::int.

Taught in Scalars and Strings.

Decimal (§4 Primitive Types) has +, -, *, /, %, the comparisons and equality. +, - and * never round. The scale grows as needed: 1.50d + 1.5d == 3.00d and 1.50d * 1.5d == 2.250d.

/ rounds. A quotient is kept to 34 significant digits, rounded half-even, which is IEEE 754 decimal128’s precision (Java’s MathContext.DECIMAL128): enough for any amount of money and any rate applied to it.

  • The digits are counted from the quotient’s first non-zero digit, so 1d / 3000d keeps 34 threes after 0.000.
  • A quotient is never rounded left of the decimal point: one whose whole part has more than 34 digits keeps all of them, at scale 0.
  • The result has no trailing zeros after the point. A quotient that ends within its 34 digits is therefore exact, at the smallest scale that holds it, whatever the operands’ scales: 10.00d / 4d is 2.5d, 1d / 4d is 0.25d and 6.00d / 3d is 2d. Decimal.scale reads that scale (1, 2 and 0) and Decimal.to_string prints it ("2.5", "0.25", "2").
  • A quotient that does not end has all 34 digits: 10d / 3d is 3.333333333333333333333333333333333d and 2d / -3d is -0.6666666666666666666666666666666667d.
  • The divisor is a NonZeroDecimal, as Int’s is a NonZeroInt: d / e with e a Decimal is `/` divides by a NonZeroDecimal; `e` is a Decimal until a check (if e == 0d then ...) or a type says it is not zero.
  • Divide.divide(a, b) and Decimal.divide(a, b) are the same operation, and Decimal meets a Divide<NonZeroDecimal, Decimal> bound.
  • / takes two Decimals, as * does: 1d / 3 is `/` needs two values of one type, and these are Decimal and Int, whose help writes 3d.

std::decimal’s Decimal.divide(a, b, scale, mode) rounds to a scale and RoundingMode you name, for an answer whose digits are fixed (cents, a rate to four places). Decimal.divide_exact returns None for a quotient that does not end, and Decimal.round_exact and Decimal.sqrt_exact return None where a digit would be lost; no RoundingMode asserts exactness.

% is exact: a - b * q, where q is the quotient truncated toward zero. It takes the sign of a, never rounds, and has the larger of the two scales: 10.5d % 3d == 1.5d, 7.25d % 0.5d is 0.25d, -7.5d % 2d == -1.5d and 10d % 2.50d is 0.00d. Its divisor is a NonZeroDecimal, as /’s is.

Equality and comparison are by value and ignore scale: 1.50d == 1.5d is True. Scale is kept for display: Decimal.scale(1.50d) == 2 and Decimal.to_string(1.50d) == "1.50".

Taught in Interfaces and Dispatch.

+, -, *, / and % are the prelude interfaces Add<Rhs, Out>, Subtract<Rhs, Out>, Multiply<Rhs, Out>, Divide<Rhs, Out> and Remainder<Rhs, Out>. The left operand is the implementing type. The type arguments name the right operand’s type and the result’s:

interface Add<Rhs, Out>
    fn add(lhs: self, rhs: Rhs) -> Out
end
type Day Int
type Days Int

impl Add<Days, Day> for Day
    fn add(lhs: Day, rhs: Days) -> Day
        Day(d) = lhs
        Days(n) = rhs
        Day(d + n)
    end
end

fn main()
    dbg Day(3) + Days(4) // Day(7)
end
  • One receiver may implement an operator several times, told apart by the right operand’s type (§12 Several instantiations for one type): Instant - Duration is an Instant and Instant - Instant a Duration.
  • std implements arithmetic for Int, Float and Decimal, and Add for String and Bytes. Int’s and Decimal’s Divide and Remainder take a NonZeroInt and a NonZeroDecimal (Integer division and remainder). Duration has Divide<NonZeroInt, Duration> and Remainder<NonZeroDuration, Duration>: elapsed % Duration.minutes(15) is how far into the current quarter hour elapsed is.
  • Generic code that uses an operator names the bound: where T: Add<Step, Out>.
  • An operator impl may be generic over the receiver’s type parameters. Its interface arguments are read at the left operand’s type, so impl Add<Set<T>, Set<T>> for Set<T> makes Set[1, 2] + Set[2, 3] a Set<Int>. A right operand no impl takes is an error: Set[1] + 2 is binary + right operand mismatch: Add expects Set<Int>, got Int.
  • An operand type with no impl is an error at the operator that names the interface: no impl of `BitwiseAnd` for `Float` (required via bitwise and operator `&&&`), and for a type Score Int with no Remainder, no impl of `Remainder` for `Score` (required via remainder operator `%`).

Summable. A type whose + takes two of its values and returns one may implement the prelude interface Summable. empty_sum() is the sum of no values, the value + leaves alone: T.add(x, T.empty_sum()) == x.

interface Summable
    fn empty_sum() -> self
end

Interfaces do not extend one another (§12), so code that sums names both bounds, where T: Add<T, T> and Summable, as Iter.sum does. std::summable lists the std types that implement it.

Productable. The same for *: empty_product() is the product of no values. Iter.product is bounded by where T: Multiply<T, T> and Productable, and std::productable lists the std types that implement it.

interface Productable
    fn empty_product() -> self
end

Averageable. Iter.mean and Iter.mean_by are bounded by where T: Averageable<R>: mean(values) is the mean of values as an R, None when there are none, and the impl’s R is the result’s type, so a call solves it from the element type. Int’s mean is a Float, the exact sum over the count rounded once; Float’s sums with compensation; Decimal’s is a Decimal and Duration’s a Duration. A subtype has its base’s impl, so the mean of NonNegativeInts is a Float. std::averageable gives each std impl’s rounding.

interface Averageable<R>
    fn mean(values: Iter<self>) -> Maybe<R>
end

&&& (and), ||| (or), ^^^ (exclusive or), ~~~ (prefix not), <<< (shift left) and >>> (arithmetic shift right).

fn main()
    byte = 0b1010_0000
    dbg byte >>> 7 &&& 1 // (byte >>> 7) &&& 1 == 1
    dbg 1 <<< 64         // 18446744073709551616
    dbg -1 &&& Int.pow(2, 80) == Int.pow(2, 80) // True
end
  • On Int the operators read the value as two’s complement with as many bits as it needs, a negative value having endless leading ones. So &&&, |||, ^^^ and ~~~ give exact results at any size, and ~~~n == -n - 1.
  • a <<< n is a times 2 to the n, exact: no bit is shifted out.
  • a >>> n divides by 2 to the n, rounding toward negative infinity. A count past a’s bits returns 0 for a non-negative a and -1 for a negative one.
  • The count is a NonNegativeInt (impl ShiftLeft<NonNegativeInt, Int> for Int), held to it as a divisor is to NonZeroInt (§8 Integer division and remainder): with n an Int, 1 <<< n is `<<<` shifts by a NonNegativeInt; `n` is an Int with the help check it first (`if n < 0 then ...`) or take a NonNegativeInt. A left shift whose result would not fit in memory traps.
  • Byte has &&&, |||, ^^^ and ~~~, whose results stay within 8 bits (~~~b is 255 - b). It has no shift, since a left shift could carry bits past 8: shift the Int (Byte.to_int(b) <<< 1). b <<< 1 is no impl of `ShiftLeft` for `Byte` (required via shift left operator `<<<`).
  • The C-family spellings are parse errors that name the Nomi one: a << n is Nomi spells shift left `<<<`: write `a <<< n`, not `a << n` , and the same for >>. A >> or >>> that closes nested type arguments (List<List<List<Int>>>) is still closing brackets.

The operators dispatch through prelude interfaces as + does through Add: BitwiseAnd<Rhs, Out>, BitwiseOr<Rhs, Out>, BitwiseXor<Rhs, Out>, ShiftLeft<Rhs, Out> and ShiftRight<Rhs, Out>, each with one function named for its operation (fn bitwise_and(lhs: self, rhs: Rhs) -> Out), and BitwiseNot<Out> with fn bitwise_not(value: self) -> Out. A distinct type opts in with an impl:

type Flags Int

impl BitwiseOr<Flags, Flags> for Flags
    fn bitwise_or(lhs: Flags, rhs: Flags) -> Flags
        Flags(a) = lhs
        Flags(b) = rhs
        Flags(a ||| b)
    end
end

Int.bitwise_and(a, b) and the other five are the Int impls’ functions, for passing as values (Iter.reduce(flags, 0, Int.bitwise_or)).

==, !=, <, >, <= and >=.

  • == and != take two operands of one type. Equality is structural unless the type has a hand-written impl Equatable (§5 Equality and Ordering Semantics). Two operands of different types are a compile error, not False: "a" == 1 is equality type mismatch: String vs Int.
  • <, >, <= and >= need the operand type to implement Comparable, through derive Comparable or an impl. Without one they are an error: no impl of `Comparable` for `P` (required via ordering operator `<`).
  • The operands are a determining position for each other (§5): k == .Deposit resolves .Deposit against k’s enum.

and, or and prefix not. Each takes and returns Bool.

  • not x is True when x is False. An operand of another type is an error: `not` takes a Bool, got Int.
  • not’s operand is everything to its right that binds at least as tightly as ==. not a == b is not (a == b), not a < b and c is (not (a < b)) and c, and not a and b is (not a) and b. A pipeline binds more tightly than a comparison, so not xs |> Iter.is_empty() is not (xs |> Iter.is_empty()). not ready()? is not (ready()?). not not x is x.
  • A not stands alone, after and or or, or after another not. As the operand of a tighter operator it is an error: a == not b is `not` binds looser than comparisons and arithmetic, so it cannot be their operand, whose help shows a == (not b). The same holds for -not x and a capture body &not f(&1) (write &(not f(&1))).
  • a and b is if a then b else False, and a or b is if a then True else b: the right operand runs only when the left does not decide the result. The right operand may leave instead of returning (a block ending in return, break or continue, an if or case every arm of which leaves, a failing ?, a trap). On that path the expression has no value; on the other its value is the left operand’s.
fn ready(flag: Bool) -> Result<Bool, String>
    ok = flag
        or begin
            return Err("not ready")
        end

    Ok(ok)
end

fn main()
    dbg ready(False) // Err("not ready")
    dbg ready(True)  // Ok(True)
end
  • A pipe stage may start with not, which negates the stage’s result: name |> not Iter.is_empty() is not Iter.is_empty(name), and the stages after it take the negated value. The stage is a call, possibly unwrapped with ! (flags |> not Iter.first()!), or another not stage. A ? there is an error, since it would propagate the call’s failure rather than the negation’s: a `not` stage cannot end in `?`: the `?` would propagate the call's failure, not the negation's.
  • The C-family forms are parse errors that name the Nomi one: !x is Nomi spells logical not `not`: write `not x`, not `!x` , a && b is Nomi spells logical and `and`: write `a and b`, not `a && b` , and a || b is Nomi spells logical or `or`: write `a or b`, not `a || b` .

Taught in Pattern Matching.

value is Pattern is a Bool: whether the value matches the pattern. It returns what a case with a True arm for the pattern and a _ -> False arm returns.

enum Block
    Item String
    Text String
end

fn main()
    blocks = [Block.Item("milk"), Block.Text("note"), Block.Item("eggs")]
    dbg blocks |> Iter.filter(&(&1 is .Item(_))) |> Iter.count() // 2
    dbg 3 is (1 or 2)                      // False
    dbg not [1, 2] |> List.first() is None // True
end
  • Precedence. is binds as == does: looser than |>, ranges and arithmetic, so xs |> List.first() is Some(_) tests the pipeline’s result, and tighter than not, and and or, so not block is .Item(_) is not (block is .Item(_)).
  • It does not chain. a == b is True is `is` does not chain with a comparison, whose help shows (a == b) is True. An operator that binds more tightly than is, written after the pattern, is an error too, since a pattern is not an expression: x is 1 + 1 is an `is` test's pattern ends before `+`, and x is P |> f() is an `is` test's pattern ends before `|>`.
  • The pattern is a case arm’s. Every pattern form works, nested to any depth (§10). It is checked against the value’s type with an arm’s errors: a .Variant resolves against the value’s type, and n is "x" over an Int is pattern "x" is a String, but the value is an Int. A map pattern’s keys are evaluated where the test is.
  • It binds nothing. A name in the pattern is the error an `is` test binds nothing, so its pattern cannot name `n`, whose help names the binding form, if Some(n) = m then .... When the whole pattern is the name, the help is to compare the value with `n`, write `m == n` . An as name is the same error. A discard name (_rest) is allowed.
  • An or pattern goes in parentheses: kind is (.Circle or .Square). A bare or after the pattern is the Boolean or, so x is .A or y > 0 is (x is .A) or (y > 0). When the right side can only be a pattern (_, a .Variant, .B(...) or .B{...}), it is the parse error this `or` joins two Bool values, and a pattern cannot be its right operand: `is` takes one pattern. When the right side is read as a Bool and is not one, the 'or' operands must be Bool error’s help names the parenthesized form.
  • A pattern that always matches is an error, since the test could only return True: `_` matches every value of type Kind, so this test is always True. There is no exhaustiveness to check.
  • The value is evaluated once, before the pattern is tested.
  • There is no is not: x is not 1 is `is not` is not an operator, whose help says to write not x is P.

x in c is True when the collection c holds x. It is Contains.contains(c, x) written as an operator, and calls the same impl.

interface Contains<T>
    fn contains(c: self, x: T) -> Bool
end

The std collections implement it: a Set holds its members, a Map its keys, a Range the values between its ends, a List, Vector or Bytes its elements, and a String a substring, a Regex match or a Codepoint. std::contains says how each one looks and what it costs.

fn main()
    dbg 2 in [1, 2, 3]    // True
    dbg "a" in {"a" => 1} // True: a map holds its keys
    dbg 10 in 1..10       // False: the end is excluded
    dbg '-' in "a-b"      // True
    dbg not 7 in [1, 2]   // True
end
  • Precedence. in binds as == does: looser than |>, ranges, arithmetic and the bitwise operators, so x in 1..10 is x in (1..10) and id in ids |> Iter.to_set() looks in the set, and tighter than not, and and or, so not id in seen is not (id in seen).
  • It does not chain. a == b in flags, x in xs == b, x in a < b, x in xs is True and x in xs in ys are parse errors that ask for parentheses (`in` does not chain with `==`).
  • There is no not in: x not in xs is `not in` is not an operator, whose help says to write not x in xs.
  • Any type with a Contains impl supports in, and so does a type parameter bounded by Contains<T>. String implements Contains at three type arguments, and a call takes the one its argument’s type chooses (§12 Several instantiations for one type).
  • A collection with no impl is an error that names the operand: the collection `in` looks in: Bag does not implement Contains. A value the impl does not take is the value `in` looks for: expected Int, got String for "a" in [1, 2], and 1 in {"a" => 1} is the value `in` looks for: expected String, got Int.
  • List and Vector implement Contains where their element is Equatable, which every type with equality is (§5 Equality bounds): p in [p] and p in Vector[p] take a struct P with no impl of its own, as p in Set[p] and p in {p => 1} do. An element type with no equality is one error, the element’s, at the collection: o in [o] for a struct Op holding a function is no impl of `Equatable` for `Op` (required via membership test `in`). A program’s impl with a bound on its element is reported the same way.
  • Elements compare as == does, so Float equality is reflexive here (§5 Equality): a NaN element is found by NaN.
fn all_present<C, T>(c: C, wanted: List<T>) -> Bool where C: Contains<T>
    Iter.all_match(wanted, &(&1 in c))
end

fn main()
    dbg all_present("a word", ["a", "word"]) // True: String's impl at String
    dbg all_present("a-b", ['-'])            // True: its impl at Codepoint
end

Taught in Structs, Enums and Distinct Types.

value.field reads a struct’s or an anonymous struct’s field, and value.first, value.second, … a tuple’s item (§4 Tuples). Access chains: user.address.city.

  • A value of interface type or of type-parameter type has no fields (§14 Member access is fail-loud).
  • Where a function is expected, .name with nothing before the dot is a function that reads the field (users |> Iter.map(.name), §7 Field Accessors).
  • . also qualifies names (users.new, Iter.map). A qualifier is resolved at compile time; field access is an operation on a value.
  • There is no per-field visibility. A field is reachable wherever its struct is visible.

Taught in Interfaces and Dispatch.

Nomi has no methods. Every call of a declared function is a qualified call Q.f(args) or a bare call of a name in scope, never x.f(). The qualifier names a file, a type, an interface or a bounded type parameter:

  • A file-level function is qualified by its file: io.print(x), users.create(name, age).
  • An inherent function (in an impl Type block) is qualified by its type: String.trim(s), Duration.seconds(1).
  • An interface impl’s function is qualified by the implementing type (User.to_string(u)), by the interface (Display.to_string(u)) or by a type parameter bounded by the interface (T.to_string(x), §12).
  • File qualification never reaches into an impl block. users.to_string(u) is the error file 'users' has no member 'to_string', whose help names the owner: it implements Display for User, so call it as User.to_string(...) or Display.to_string(...).
  • A bare call of an interface function (to_string(u)) is an error. Inside an impl block, sibling functions are called bare.

An interface-qualified call selects the impl for the concrete type bound to self by the arguments, or by an explicit type argument for a function with no self parameter (FromJson.from_json<User>(json)). A pipe chains qualified calls: x |> Shape.area() |> Display.to_string().

Taught in Pipes.

x |> stage passes x to the stage. The value of the pipeline is the last stage’s.

  • A call stage. x |> f() is f(x) and x |> f(a) is f(x, a): the value fills the first argument, and is checked as that argument is, so a pipe accepts what the call accepts: with fn show(fs: List<(Int) -> Display>), [number, word] |> show() builds that list as show([number, word]) does. A .Variant stage is written through its enum (x |> Shape.Dot()), since a bare .Variant cannot see its enum.
  • A name is not a stage. A name without parentheses is a function reference, so x |> f, x |> io.print, x |> Ok and x |> Shape.area are errors that name the call to write: a pipe stage is a call: write `io.print()`.
  • The value fills only the first argument. An &N in a call stage stands outside every capture, so x |> divide(100, &1) is two errors: expected 2 arguments, got 3 (counting the piped value), and `&1` is a capture's parameter: write the function as `&(...)` or `&f(...)`, whose help says a pipe fills the first argument; write `|> then &divide(100, &1)`.
  • A stage that does not take the value is an error at the stage that names the argument the value fills, with a note at the value’s source: `String.pad_start` takes a String as its first argument, but the pipe passes a Fahrenheit. When the value’s type implements Display and the stage takes a String, the help says to add |> Display.to_string() first.
  • A ? after a stage propagates that stage’s Err or None and passes the value inside to the next stage (id |> User.get()? |> User.profile()). It may follow a call stage or the end of an if or case stage. A ? inside a stage’s parentheses is an error: t |> (String.to_int()?) is a `?` inside a stage's parentheses applies before the pipe passes its value: write the `?` after the stage, as in `|> f()?`.
  • A ! after a stage unwraps its result: text |> String.to_int()! |> Int.abs() (§11 Unwrapping with !).
  • A lambda body runs to the end of its expression, or to the ), ], } or , that closes the construct it stands in. A |> inside it belongs to the body: in Iter.map(xs, fn s -> String.to_int(s) |> Maybe.with_default(0)) the pipe is the lambda’s. The exception is the lambda of a then or tap stage.
  • A lambda or a capture is not a stage without then: xs |> fn n -> n * 2 is a lambda is not a pipe stage: write `then fn n -> ...`, and x |> &f(&1) is a capture is not a pipe stage: write `then &f(&1)`.

then and tap are reserved words. tap stands only after |>, and then after |> or as an if’s (§8 if/else).

Taught in Pipes.

x |> then fn v -> body applies the lambda to the piped value, as (fn v -> body)(x) would. x |> then &f(a, &1) applies the capture, as (&f(a, &1))(x) would, and x is checked as f’s argument at the &1.

fn divide(a: Int, b: NonZeroInt) -> Int
    a / b
end

fn add(a: Int, b: Int) -> Int
    a + b
end

fn main()
    dbg 10 |> then &divide(100, &1) // 10
    dbg 3 |> then &add(&1, b: &1)   // 6

    dbg (1, 2)
    |> then fn (a, b) -> a + b // 3
end
  • then is followed by a lambda or a capture. Anything else is the parse error `then` takes a lambda or a capture: write `then fn v -> ...` or `then &f(&1)`. For a function by name, x |> then f would be x |> f(), so it is that error with the help write `|> f()` for a function by name.
  • The function takes one parameter, the piped value. A lambda’s parameter may be a destructuring pattern. A capture’s is &1, which may stand anywhere, positional or named, as often as it is written, and is computed once: x |> then &connect(port: &1, "localhost") is connect("localhost", port: x). A second parameter is an error: then &add(&1, &2) is the function expected here takes one argument; `&2` names a second.
  • A capture ends with its body, so 10 |> then &divide(100, &1) |> dbg divides and then prints.
  • A bare lambda body ends at the next |> of the pipeline, so the stages after it stay in the pipeline. A body written below then fn v -> and closed by end keeps a pipe inside it, and so do parentheses: |> then fn v -> (v |> Iter.filter(.is_paid) |> Iter.count()). A parameter of a bare then body used in a later stage is an error that says where the body ended.
  • A partial capture that does not take the value at its &1 is reported at the &1, as a call stage is: `label` takes a String as its second argument, or for a named &1, `label` takes a String as `text`, but the pipe passes an Int.
  • then? is a then stage followed by a ?: text |> then? fn t -> parse(t, 16) applies the function and propagates an Err or None in its result. A ? at the end of the lambda’s body belongs to the body and exits the lambda.

Taught in Pipes.

x |> tap fn v -> body runs the lambda on the piped value for its effect and passes the value on unchanged. x |> tap io.print does the same with a function by name, and x |> tap &log(level, &1) with a capture. The value is computed once and the function runs once, at that point in the pipeline.

import std::io

fn main()
    shout =
        "go north now"
        |> String.words()
        |> tap fn words -> io.print("got ${Iter.count(words)} words")
        |> Iter.map(String.uppercase)
        |> String.join(" ")
        |> tap io.print

    io.print(String.length(shout))
end

This prints got 3 words, then GO NORTH NOW, then 12.

  • The lambda follows the then rules: one parameter, which may be a pattern; a bare body ends at the next |>.
  • The lambda returns Unit. A body of another type is `tap` passes its input on unchanged, so its lambda must return Unit; got Int, whose help says to use then. A body may end in a dbg observation, as a Unit function body may (§9).
  • A function by name is a plain name (log_it), a qualified one (io.print, Log.info) or a local binding that holds a function, perhaps in parentheses: tap (log_it) is tap log_it. Only a name may stand in them; tap (fn v -> ...) is the parse error below. It is typed as a function value passed where (T) -> Unit is expected, T the piped value’s type: a generic function is instantiated from the piped value, and a function whose parameters after the first all have defaults is called with them filled (§7 Default Arguments). Any other function is an error at the name: a `tap` function takes one parameter, the piped value; `pair` takes 2, `says` takes a String, but the pipe passes an Int, or `tap` passes its input on unchanged, so its function must return Unit; `double` returns Int, whose help says to call it as a stage, |> double(). A name that holds no function is `tap` takes a function, but `count` is an Int. Anything after tap other than a name, a lambda or a capture is the parse error `tap` takes a function: write `tap f`, `tap fn v -> ...` or `tap &f(&1)`.
  • A ? or return in the lambda exits the lambda, so a body that uses ? returns a Result or Maybe and is rejected.
  • tap? is `tap` passes its input on unchanged, so there is no result for a `?` to propagate, whose help says to handle the failure inside the lambda or use then?.

Taught in Pipes.

dbg, if and case consume one piped value. Each is a bare stage, or prefixes the one call stage that computes its operand, condition or scrutinee:

status
|> if Status.is_ready() then "go" else "wait"

input
|> case parse_id()
    Ok(id) -> id
    Err(_) -> 0
end

input |> case parse_id() and input |> parse_id() |> case, each above the same arms, are the same program. An assertion wraps a pipeline from its head (assert message |> String.contains("ready"), §17).

Taught in Bindings and Expressions.

begin, statements on the lines below, and end is an expression whose value is its last statement’s. A block stands anywhere an expression does: a function argument, a pipe’s head, a binding’s value. begin end is the empty block, whose value is Unit.

fn main()
    total = begin
        x = 2
        y = 3
        x + y
    end

    dbg total // 5
end
  • Bindings inside a block are scoped to it. This holds for every body: an if or else branch, a case arm, a begin block, a lambda body, a concurrent body. A defer inside a begin block runs at its end.
  • A binding that shadows an outer name hides it until the block ends; a read after the block reads the outer binding. So an inner binding nothing in its block reads is the error binding 'total' is never read.
  • A block whose last statement is a binding has the value Unit.
  • The statement rules are in §9.

Taught in Bindings and Expressions.

if condition then ... else ... is an expression. The condition is a Bool, written without parentheses. It has two forms, told apart by what follows then on its line:

  • Block form. A then that ends its line takes the lines below as the branch, up to else or end. An else that ends its line takes the lines below to end. else if c then chains further branches, and the chain shares the one end that closes its last branch.
  • Inline form. Anything after then on its line makes the if one expression on that line, with no end: sign = if n < 0 then "-" else "+". Each branch is one expression, or break, continue or return. The else stands on the same line, and its branch extends as far right as an expression does, as a lambda’s body does: if c then a else b |> f pipes b alone, and (if c then a else b) |> f pipes the if. A ,, ), ] or the end of the line ends it. else if chains work inline, and an if with no else is inline too: if verbose then log("x").

An inline if is single-line only: an else on the next line is an error, and nomi fmt writes an inline if too wide for its line in block form.

fn sign(x: Int) -> String
    if x > 0 then
        "positive"
    else if x == 0 then
        "zero"
    else
        "negative"
    end
end

fn main()
    dbg sign(-3) // "negative"
end
  • A condition that checks a binding against a constant, or tests it for emptiness, narrows it to a std subtype in each branch (§4 Narrowing): in if d != 0 then n / d else 0, d is a NonZeroInt in the first branch, and after if d == 0 then return 0, in the rest of the block.
  • An if without else, and an else if chain with no final else, is a statement, of type Unit. Its branch is Unit, leaves (return, break, a ? that propagates, a call that never returns), or ends in an assert, refute or dbg, whose value a block drops. So if debug then log.debug("x"), if n < 0 then return Err(e) and if on then assert n > 0 are statements.
  • A branch of any other type is an error at the branch’s value, a Maybe included. A value that may be absent is written with its else: if c then Some(x) else None. A fn first_even(n: Int) -> Maybe<Int> whose body is if n % 2 == 0 then Some(n) is an `if` without `else` is a statement, so its branch must be `Unit`; this branch is a `Maybe<Int>`. Add `else None` to make the `if` a `Maybe<Int>` , and an editor’s quick fix adds the else None. Any other branch says to add an else: if n > 0 then "positive" is ... this branch is a `String`. Add an `else` to give the `if` a value. Where a statement drops the branch’s value, before a block’s end or at the end of a Unit function, the error says ... this branch is an `Int`, which this statement drops. Write `_ = n + 1` in the branch, or add an `else` , and the quick fix writes the _ = .
fn sign(n: Int) -> Maybe<String>
    if n > 0 then
        Some("positive")
    else if n < 0 then
        Some("negative")
    else
        None
    end
end

fn main()
    dbg sign(3) // Some("positive")
    dbg sign(0) // None
end
  • The branches have one type. Two types are the error if/else branch type mismatch: then is Range<Int>, else is List<Int>. Two joins need nothing written: a concrete type beside an interface it implements is the interface, and a type beside an enum that embeds it is the enum.
  • Two types that both implement an interface join as that interface only where the value’s type is written as it: a binding’s annotation, a parameter’s type or a function’s declared result. Any interface joins this way, std’s or the program’s, generic or not: s: Shape = if round then Circle{r: 1.0} else Square{side: 2.0} is a Shape, d: Display = if n > 0 then n else "none" is a Display, and a Range beside a List under a written Iter<Int> is an Iter<Int>. Each branch’s value enters the interface as any value assigned to it does. The same holds for every arm of a case. A pipe’s head is its first stage’s first argument, so (if up then 1..4 else [3, 2, 1]) |> Iter.count() joins at Iter.count’s Iter<T> parameter.
  • Without a written interface the mismatch stands, and its help may name the annotation. When both branches are an Iter of one element type, the help is both are an Iter<Int>, and two kinds of Iter join only where the value's type is written as one: annotate it `: Iter<Int>`, or declare the function's result as `Iter<Int>` . When exactly one interface declared outside std, with no type parameters, is implemented by both types, the help names it: both implement Shape, and two types join as an interface only where the value's type is written as one: annotate it `: Shape`, or declare the function's result as `Shape` . No std interface but Iter is named, since nearly any two types share Display, Debug and Equatable, and two candidate interfaces give no help.
fn in_order(values: Range<Int>, descending: Bool) -> Iter<Int>
    if descending then Iter.reverse(values) else values
end

Pattern if. if Pattern = value then ... else ... runs the first branch when the value matches the pattern, with the pattern’s names bound there only, and the else branch otherwise. Without else it is a statement, as an if without else is: if Some(n) = m then io.inspect(n).

fn label(maybe_name: Maybe<String>) -> String
    if Some(name) = maybe_name then
        name
    else
        "unknown"
    end
end

The pattern must be able to fail. One that matches every value of the type (a name, _, a tuple of names, a struct or distinct destructure, a single-variant enum) is the error this pattern always matches a value of type Int, so the `if` has nothing to test; bind it on its own line with `pattern = value` . When if x = 0 names an x of the value’s type already in scope, the help says to write if x == 0.

Taught in Pattern Matching.

case value, its arms on the lines below and end, matches the value against each arm’s pattern in order and has the value of the first arm that matches. An arm is Pattern -> body or Pattern when guard -> body (§10 Guards). The arms must be exhaustive (§10 Exhaustiveness checking).

case alone on its line, with no value, is a conditional. Each arm is condition -> body, and the first arm whose condition is True runs. A condition is a Bool: x + 1 -> ... is case condition must be Bool, got Int. The arms must end with _ -> body, since conditions cannot be shown exhaustive: without one the error is non-exhaustive case: add a `_` arm. An arm’s body runs where its condition is true and every earlier one false, which narrows the bindings they check (§4 Narrowing): after n < 0 and n == 0, the _ arm’s n is a PositiveInt.

fn size(x: Int) -> String
    case
        x > 10 -> "big"
        x > 0  -> "positive"
        _      -> "not positive"
    end
end

fn main()
    dbg size(4) // "positive"
end
  • The arms have one type, by the rules for if branches.
  • Each arm starts its own line. A body on the ->’s line is one expression. A -> that ends its line takes the lines below as the body, up to the next line that starts an arm or the case’s end, as Elixir reads an arm. A line starts an arm when what stands before its first -> outside brackets is a pattern with an optional when guard; a statement is never one, since a pattern holds no = and a lambda’s -> stands inside a call’s parentheses. Indentation decides nothing.
fn describe(n: Maybe<Int>) -> String
    case n
        Some(x) when x > 9 ->
            digits = Int.to_string(x)
            "big: ${digits}"

        Some(x) ->
            "small: ${x}"

        None ->
            "none"
    end
end

fn main()
    dbg describe(Some(42)) // "big: 42"
end
  • case e end on one line has no arms, for a value of a type with none.
  • break, continue and return may be an arm’s body (§9).
  • case is a pipe stage (Keyword stages).

dbg expr prints a Debug rendering of expr with its source line and source text, and has the value of expr. |> dbg is the same as a pipe stage, and passes the value on.

fn main()
    total =
        [1, 2, 3]
        |> Iter.map(&(&1 * 2))
        |> Iter.to_list()
        |> dbg // prints the list and passes it on
        |> Iter.sum()

    dbg total + 1 // prints `dbg line 9: total + 1 = 13`
end
  • The rendering is Debug.inspect’s, as io.inspect prints it (§12 Display and Debug).
  • A parenthesized dbg expr is the value of expr, not a stage: x |> (dbg 1) is the error a parenthesized `dbg expr` is not a pipe stage: it is the value of `expr`, and the pipe has nothing to call, whose help names |> dbg.
  • A dbg may be a non-final statement, and may end a Unit body (§9 Statements and the Unit rule).
  • dbg is for development: nomi build refuses a program that holds one (tooling reference).