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.
Evaluation order
Section titled “Evaluation order”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
Operators and precedence
Section titled “Operators and precedence”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:
| Level | Operators |
|---|---|
| 1 | or |
| 2 | and |
| 3 | prefix not |
| 4 | == != is in |
| 5 | < > <= >= |
| 6 | |> as |
| 7 | .. ..= |
| 8 | + - ||| ^^^ |
| 9 | * / % &&& <<< >>> |
| 10 | prefix - ~~~ |
| 11 | calls, field access, postfix ? and ! |
- Binary operators of one level associate to the left.
- The bitwise levels are Go’s:
x &&& mask == 0is(x &&& mask) == 0, andhi <<< 8 ||| lois(hi <<< 8) ||| lo. isandinbind as==does but do not associate. Neither chains with==,!=, an ordering operator,isorin(Pattern test:is, Membership:Contains).- Prefix
nottakes everything to its right that binds at least as tightly as==(Logical operators). astakes a type, not an expression, on its right, and ascribes everything to its left at its level, soxs |> Iter.to_list() as List<Int>ascribes the pipeline anda == b as Tisa == (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).
Arithmetic operators
Section titled “Arithmetic operators”Taught in Scalars and Strings.
+, -, *, / and %, and prefix -.
-
Int,FloatandDecimalhave+,-,*,/,%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.0and1 == 1.0are 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 withInt.to_float,Float.to_int,Int.to_decimal,Decimal.to_floatorFloat.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: withcountaNonNegativeInt,count + 1is aPositiveIntandcount - 1anInt(§4 Arithmetic on numeric subtypes). -
+on twoStringor twoBytesvalues concatenates. -
On collections,
+and-combine two collections of one type.List<T> + List<T>andVector<T> + Vector<T>concatenate.Set<T> + Set<T>is the union andSet<T> - Set<T>the difference.Map<K, V> + Map<K, V>isMap.merge: on a shared key the right-hand value wins.Maphas no-. There is no collection-plus-element form: writes + Set[x],list + [x]orm + {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)] + routesis aList<(Route, Handler)>thoughhomeis a(Request) -> Response. Two operands that each have a type of their own must have one type: withmine = [(Route`GET /`, home)],mine + routesis the error that+needs two values of one type.
Integer arithmetic is exact
Section titled “Integer arithmetic is exact”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))isNone,Iter.take(xs, Int.pow(10, 30))takes all ofxs, andVector.get(v, Int.pow(10, 30))!traps as any index out of range does. - A Go function bound with
go(§19) that takesint64,intor 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 plainIntthere is an error at the binding (§19 How Nomi types project to Go), soInt64.try_from(n)checks a computed value before the call. A Gouint64result past 64 signed bits is an exactInt. A Go*big.Intparameter or result takes anyInt, and a nil*big.Intresult 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
Intits engine cannot store. ADurationis anIntof nanoseconds with no range, and anInstantanIntof nanoseconds from the epoch with none, soInstant + Durationnever 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: aDate’s year is anIntof any size, anOffsetDateTimeorDateTimeholds anyInstant, 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 everyparsereads it back. std::json reads and writes anIntof any size, and anexport fnresult past ±2⁵³ fails the call (§7 Exported Functions).
Integer division and remainder
Section titled “Integer division and remainder”/ 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 areDivide<NonZeroInt, Int>andRemainder<NonZeroInt, Int>, andInt.divideandInt.remaindertake one. A divisor passes when it is a non-zero literal, when its type isNonZeroIntor below it, or when its range proves it off zero (§4 Value ranges): a binding checked first (§4 Narrowing),n + 1withnaNonNegativeInt,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 Intwith the helpcheck it first (`if elapsed == 0 then ...`) or take a NonZeroInt. A divisor that is always zero isdivision by zero: the divisor is the literal 0, or withzero = 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
Intby zero. The VM still checks each division and stops withline N: division by zero(§11 Traps,MaybeandResult), a backstop no checked program reaches. - A generic function that divides by its own type,
where T: Divide<T, T>, does not take anInt, whose/takes aNonZeroInt; one bounded by the divisor’s type does:fn rem<T, D>(a: T, b: D) -> T where T: Remainder<D, T>takesrem(10, NonZeroInt(4)). - The named functions that divide take a non-zero divisor too:
Int.modulo(x, y)andInt.floor_div(x, y)aNonZeroInt, andDecimal.divideandDecimal.divide_exactaNonZeroDecimal, soInt.modulo(x, 0)is0 is not a NonZeroInt: `fn n -> n != 0` is false. - An impl of
DivideorRemainderfor a type of one’s own takes a divisor that cannot be zero in the same way: aNonZeroInt(impl Divide<NonZeroInt, Score> for Score, soscore / 4), or a subtype of its own type whose rule rules zero out (impl Divide<NonZeroRational, Rational> for Rational). Its body divides anIntunder the same rule as any other code. Float’s%is IEEE 754’s fmod:a - b * trunc(a / b)computed exactly, with the sign ofa(-7.5 % 2.0 == -1.5). It never traps: a zero divisor or an infinite dividend gives NaN, and an infinite divisor givesa.
Floored division and modulo, powers, roots and digits are functions in std::int.
Decimal arithmetic
Section titled “Decimal arithmetic”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 / 3000dkeeps 34 threes after0.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 / 4dis2.5d,1d / 4dis0.25dand6.00d / 3dis2d.Decimal.scalereads that scale (1,2and0) andDecimal.to_stringprints it ("2.5","0.25","2"). - A quotient that does not end has all 34 digits:
10d / 3dis3.333333333333333333333333333333333dand2d / -3dis-0.6666666666666666666666666666666667d. - The divisor is a
NonZeroDecimal, asInt’s is aNonZeroInt:d / ewitheaDecimalis`/` divides by a NonZeroDecimal; `e` is a Decimaluntil a check (if e == 0d then ...) or a type says it is not zero. Divide.divide(a, b)andDecimal.divide(a, b)are the same operation, andDecimalmeets aDivide<NonZeroDecimal, Decimal>bound./takes twoDecimals, as*does:1d / 3is`/` needs two values of one type, and these are Decimal and Int, whose help writes3d.
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".
Operators through interfaces
Section titled “Operators through interfaces”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 - Durationis anInstantandInstant - InstantaDuration. - std implements arithmetic for
Int,FloatandDecimal, andAddforStringandBytes.Int’s andDecimal’sDivideandRemaindertake aNonZeroIntand aNonZeroDecimal(Integer division and remainder).DurationhasDivide<NonZeroInt, Duration>andRemainder<NonZeroDuration, Duration>:elapsed % Duration.minutes(15)is how far into the current quarter hourelapsedis. - 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>makesSet[1, 2] + Set[2, 3]aSet<Int>. A right operand no impl takes is an error:Set[1] + 2isbinary + 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 atype Score Intwith noRemainder,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
Bitwise operators
Section titled “Bitwise operators”&&& (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
Intthe 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 <<< nisatimes 2 to then, exact: no bit is shifted out.a >>> ndivides by 2 to then, rounding toward negative infinity. A count pasta’s bits returns0for a non-negativeaand-1for a negative one.- The count is a
NonNegativeInt(impl ShiftLeft<NonNegativeInt, Int> for Int), held to it as a divisor is toNonZeroInt(§8 Integer division and remainder): withnanInt,1 <<< nis`<<<` shifts by a NonNegativeInt; `n` is an Intwith the helpcheck it first (`if n < 0 then ...`) or take a NonNegativeInt. A left shift whose result would not fit in memory traps. Bytehas&&&,|||,^^^and~~~, whose results stay within 8 bits (~~~bis255 - b). It has no shift, since a left shift could carry bits past 8: shift theInt(Byte.to_int(b) <<< 1).b <<< 1isno impl of `ShiftLeft` for `Byte` (required via shift left operator `<<<`).- The C-family spellings are parse errors that name the Nomi one:
a << nisNomi 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)).
Comparison and equality
Section titled “Comparison and equality”==, !=, <, >, <= and >=.
==and!=take two operands of one type. Equality is structural unless the type has a hand-writtenimpl Equatable(§5 Equality and Ordering Semantics). Two operands of different types are a compile error, notFalse:"a" == 1isequality type mismatch: String vs Int.<,>,<=and>=need the operand type to implementComparable, throughderive Comparableor 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 == .Depositresolves.Depositagainstk’s enum.
Logical operators
Section titled “Logical operators”and, or and prefix not. Each takes and returns Bool.
not xisTruewhenxisFalse. 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 == bisnot (a == b),not a < b and cis(not (a < b)) and c, andnot a and bis(not a) and b. A pipeline binds more tightly than a comparison, sonot xs |> Iter.is_empty()isnot (xs |> Iter.is_empty()).not ready()?isnot (ready()?).not not xisx.- A
notstands alone, afterandoror, or after anothernot. As the operand of a tighter operator it is an error:a == not bis`not` binds looser than comparisons and arithmetic, so it cannot be their operand, whose help showsa == (not b). The same holds for-not xand a capture body¬ f(&1)(write&(not f(&1))). a and bisif a then b else False, anda or bisif 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 inreturn,breakorcontinue, aniforcaseevery 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()isnot 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 anothernotstage. 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:
!xisNomi spells logical not `not`: write `not x`, not `!x`,a && bisNomi spells logical and `and`: write `a and b`, not `a && b`, anda || bisNomi spells logical or `or`: write `a or b`, not `a || b`.
Pattern test: is
Section titled “Pattern test: is”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.
isbinds as==does: looser than|>, ranges and arithmetic, soxs |> List.first() is Some(_)tests the pipeline’s result, and tighter thannot,andandor, sonot block is .Item(_)isnot (block is .Item(_)). - It does not chain.
a == b is Trueis`is` does not chain with a comparison, whose help shows(a == b) is True. An operator that binds more tightly thanis, written after the pattern, is an error too, since a pattern is not an expression:x is 1 + 1isan `is` test's pattern ends before `+`, andx is P |> f()isan `is` test's pattern ends before `|>`. - The pattern is a
casearm’s. Every pattern form works, nested to any depth (§10). It is checked against the value’s type with an arm’s errors: a.Variantresolves against the value’s type, andn is "x"over anIntispattern "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 isto compare the value with `n`, write `m == n`. Anasname is the same error. A discard name (_rest) is allowed. - An
orpattern goes in parentheses:kind is (.Circle or .Square). A bareorafter the pattern is the Booleanor, sox is .A or y > 0is(x is .A) or (y > 0). When the right side can only be a pattern (_, a.Variant,.B(...)or.B{...}), it is the parse errorthis `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 Boolerror’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 1is`is not` is not an operator, whose help says to writenot x is P.
Membership: Contains
Section titled “Membership: Contains”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.
inbinds as==does: looser than|>, ranges, arithmetic and the bitwise operators, sox in 1..10isx in (1..10)andid in ids |> Iter.to_set()looks in the set, and tighter thannot,andandor, sonot id in seenisnot (id in seen). - It does not chain.
a == b in flags,x in xs == b,x in a < b,x in xs is Trueandx in xs in ysare parse errors that ask for parentheses (`in` does not chain with `==`). - There is no
not in:x not in xsis`not in` is not an operator, whose help says to writenot x in xs. - Any type with a
Containsimpl supportsin, and so does a type parameter bounded byContains<T>.StringimplementsContainsat 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 isthe value `in` looks for: expected Int, got Stringfor"a" in [1, 2], and1 in {"a" => 1}isthe value `in` looks for: expected String, got Int. ListandVectorimplementContainswhere their element isEquatable, which every type with equality is (§5 Equality bounds):p in [p]andp in Vector[p]take a structPwith no impl of its own, asp in Set[p]andp in {p => 1}do. An element type with no equality is one error, the element’s, at the collection:o in [o]for a structOpholding a function isno 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): aNaNelement is found byNaN.
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
Field access
Section titled “Field access”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,
.namewith 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.
Calls and qualification
Section titled “Calls and qualification”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 Typeblock) 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
implblock.users.to_string(u)is the errorfile '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 animplblock, 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()isf(x)andx |> f(a)isf(x, a): the value fills the first argument, and is checked as that argument is, so a pipe accepts what the call accepts: withfn show(fs: List<(Int) -> Display>),[number, word] |> show()builds that list asshow([number, word])does. A.Variantstage is written through its enum (x |> Shape.Dot()), since a bare.Variantcannot see its enum. - A name is not a stage. A name without parentheses is a function
reference, so
x |> f,x |> io.print,x |> Okandx |> Shape.areaare errors that name the call to write:a pipe stage is a call: write `io.print()`. - The value fills only the first argument. An
&Nin a call stage stands outside every capture, sox |> 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 saysa pipe fills the first argument; write `|> then ÷(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 implementsDisplayand the stage takes aString, the help says to add|> Display.to_string()first. - A
?after a stage propagates that stage’sErrorNoneand passes the value inside to the next stage (id |> User.get()? |> User.profile()). It may follow a call stage or theendof aniforcasestage. A?inside a stage’s parentheses is an error:t |> (String.to_int()?)isa `?` 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: inIter.map(xs, fn s -> String.to_int(s) |> Maybe.with_default(0))the pipe is the lambda’s. The exception is the lambda of athenortapstage. - A lambda or a capture is not a stage without
then:xs |> fn n -> n * 2isa lambda is not a pipe stage: write `then fn n -> ...`, andx |> &f(&1)isa 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).
The then stage
Section titled “The then stage”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 ÷(100, &1) // 10 dbg 3 |> then &add(&1, b: &1) // 6 dbg (1, 2) |> then fn (a, b) -> a + b // 3 end
thenis 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 fwould bex |> f(), so it is that error with the helpwrite `|> 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")isconnect("localhost", port: x). A second parameter is an error:then &add(&1, &2)isthe function expected here takes one argument; `&2` names a second. - A capture ends with its body, so
10 |> then ÷(100, &1) |> dbgdivides 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 belowthen fn v ->and closed byendkeeps a pipe inside it, and so do parentheses:|> then fn v -> (v |> Iter.filter(.is_paid) |> Iter.count()). A parameter of a barethenbody 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
&1is 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 athenstage followed by a?:text |> then? fn t -> parse(t, 16)applies the function and propagates anErrorNonein its result. A?at the end of the lambda’s body belongs to the body and exits the lambda.
The tap stage
Section titled “The tap stage”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
thenrules: 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 usethen. A body may end in adbgobservation, as aUnitfunction 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)istap 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) -> Unitis expected,Tthe 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 aftertapother 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
?orreturnin the lambda exits the lambda, so a body that uses?returns aResultorMaybeand 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 usethen?.
Keyword stages
Section titled “Keyword stages”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).
Block expressions
Section titled “Block expressions”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
iforelsebranch, acasearm, abeginblock, a lambda body, aconcurrentbody. Adeferinside abeginblock runs at itsend. - 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.
if/else
Section titled “if/else”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
thenthat ends its line takes the lines below as the branch, up toelseorend. Anelsethat ends its line takes the lines below toend.else if c thenchains further branches, and the chain shares the oneendthat closes its last branch. - Inline form. Anything after
thenon its line makes theifone expression on that line, with noend:sign = if n < 0 then "-" else "+". Each branch is one expression, orbreak,continueorreturn. Theelsestands 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 |> fpipesbalone, and(if c then a else b) |> fpipes theif. A,,),]or the end of the line ends it.else ifchains work inline, and anifwith noelseis 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,dis aNonZeroIntin the first branch, and afterif d == 0 then return 0, in the rest of the block. - An
ifwithoutelse, and anelse ifchain with no finalelse, is a statement, of typeUnit. Its branch isUnit, leaves (return,break, a?that propagates, a call that never returns), or ends in anassert,refuteordbg, whose value a block drops. Soif debug then log.debug("x"),if n < 0 then return Err(e)andif on then assert n > 0are statements. - A branch of any other type is an error at the branch’s value, a
Maybeincluded. A value that may be absent is written with itselse:if c then Some(x) else None. Afn first_even(n: Int) -> Maybe<Int>whose body isif n % 2 == 0 then Some(n)isan `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 theelse None. Any other branch says to add anelse: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 aUnitfunction, 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 thatembedsit 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 aShape,d: Display = if n > 0 then n else "none"is aDisplay, and aRangebeside aListunder a writtenIter<Int>is anIter<Int>. Each branch’s value enters the interface as any value assigned to it does. The same holds for every arm of acase. A pipe’s head is its first stage’s first argument, so(if up then 1..4 else [3, 2, 1]) |> Iter.count()joins atIter.count’sIter<T>parameter. - Without a written interface the mismatch stands, and its help may name
the annotation. When both branches are an
Iterof one element type, the help isboth 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 butIteris named, since nearly any two types shareDisplay,DebugandEquatable, 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
ifbranches. - 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 thecase’send, as Elixir reads an arm. A line starts an arm when what stands before its first->outside brackets is a pattern with an optionalwhenguard; 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 endon one line has no arms, for a value of a type with none.break,continueandreturnmay be an arm’s body (§9).caseis 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, asio.inspectprints it (§12 Display and Debug). - A parenthesized
dbg expris the value ofexpr, not a stage:x |> (dbg 1)is the errora 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
dbgmay be a non-final statement, and may end aUnitbody (§9 Statements and the Unit rule). dbgis for development:nomi buildrefuses a program that holds one (tooling reference).