Functions, control and pipelines
Everything is an expression, every function can be called like a method, and lazy sequences are fused at compile time.
3.1 Functions and sequences
Section titled “3.1 Functions and sequences”fn fullName(u: User): String = "${u.first} ${u.last}"
fn score(xs: Int[]): Int { val total = xs.sum() return total / xs.len()}
val admins = users |> filter(u => u.roles.any(r => r is Admin)) |> map(u => u.name) |> sorted()- Return type. It follows
:, like any type annotation:fn score(xs: Int[]): Int. One keystroke instead of two, which matters when you write many. - Returned value. A block body returns its value with
return: its last expression is not returned, so that the intent can be read. The concise form is the expression body,fn square(x: Int): Int = x * x. Anif, amatchor a block keep their value (val w = if c { "a" } else { "b" }), since they are not returns. A lambda follows the same rule:x => expr, or() => { …; return v }. - Function types.
(Int, Int) => Int, with the same arrow as the lambdas that inhabit them. A parameter can bemut:(mut Int[]) => ()receives a location, which the call designates byf(&xs); a lambda expected under this type modifies its parameter in place,xs => xs.push(1). - Uniform call.
x.f(y)is equivalent tof(x, y). Every free function becomes an extension method, with no extra declaration. - Pipeline.
a |> f(b)is equivalent toa.f(b), for chains where the dotted call reads poorly: f is a method of a, or a free function through the uniform call. A method, however, cannot be called asf(a, b). - Lambdas. A single form,
parameters => body:x => x * 2,(a, b) => a + b,(a: Int) => a. The body is an expression, or a{ … }block over several lines, and the lambda is always passed inside the parentheses of the call:scope.spawn(() => { … }). - Function references.
::isBlankpasses a declared function,Char::isAsciiDigita method:line.countWhile(::isBlank),xs.map(Metadata::size). - Partial application. A
?hole in an argument list marks a place left free, and makes the call a function:f(a, ?, c)meansx => f(a, x, c), andcmp.compare(?, ?)means(a, b) => cmp.compare(a, b). A hole belongs to the call of which it is directly an argument; it can appear neither on the receiver nor in an operator. An argument fixed asmutmakes the call a[var]closure:add(&ys, ?)means[var ys] x => add(&ys, x), which does not escape; a given-up (sink) argument cannot be fixed, since the resulting function may be called several times. - Local functions. A block declares functions,
fn square(x: Int): Int = x * x, visible throughout the block like those of a module: they call one another, even further down. They are functions, not closures: they do not see the block’s variables, which a lambda would capture. _is used only in patterns (Some(_),for _ in …), never as an implicit parameter.- Sequences.
Seq<T>is lazy: a core contract that extendsIterable<T>, whose methodsmap,filter,flatMap,take,skip,takeWhile,skipWhile,enumerated,zip,chainreturn adapters, andcollect,fold,forEach,count,first,any,alltraverse them.xs.seq()returns the sequence of an array, without copying it;xs.enumerated()that of its elements and their indices. Adapters are generic values,Mapped<Filtered<ArraySeq<Int>, Int>, Int, Int>, which monomorphization and LLVM fuse into a single loop, with no intermediate collection:xs.seq().filter(f).map(g).fold(0, h)is as fast as the hand-written loop. A program type that adopts Iterable gets the methods throughimpl Seq<T> for X {}.weaver.seqhaszip(a, b)anditerate(x, f);weaver.collectionshasgroupBy, which returns a Map from each key to its elements. - Closures. They capture by value (logical copy, section 6): a captured variable is not modified in the closure, since the modification would be seen by no one. A clause at the head of the lambda takes up the conventions of 6.2 without being a parameter:
[var total] x => total += x: the closure modifies the variable itself, reassigned included;[mut names] x => names.push(x), its content only. It does not escape: it is passed directly to a function parameter received read-only,xs.seq().forEach([var total] x => total += x), and the same call does not readtotalelsewhere. An enclosing lambda that captures it also takes it by[var total].[take file] () => file.write(r)!: the closure becomes the owner, likesink, andfileis no longer used afterwards. It is the only way to capture a resource, which the closure disposes of along with itself, when its last copy disappears; its disposal must therefore not be able to fail, and the lambda body only borrows it.- What guarantees that a
mutclosure does not escape. A function-typed parameter received read-only can only be called, or passed read-only: it is stored neither in a variable nor in a field, is not returned, and a lambda that captures it is itself passed read-only. A function that keeps a callback takes it assink:fn onClick(mut self, sink handler: () => ()),Heap.new(sink by: …).
- Lambda types. A lambda takes the type of its parameters from the context (
xs.map(x => x * 2)), or from their annotations ((x: Int) => …); its result is deduced from its body. A!or afailin the body makes it aT ! E, the error being the union of what they propagate:() => "${f()!}". Where() => T ! Eis expected, a lambda that does not fail always succeeds,T ! Never:withTimeout(d, () => 6 * 7). - Named and default parameters.
fn connect(host: String, port: Int = 5432), callconnect(host: h). Named arguments follow positional ones, in any order. A default value is evaluated at each call that omits it, in the scope of the function: it sees the names of its module, not those of the caller, and the read-only parameters that precede it,selfincluded.fn pad(text: String, width: Int = text.byteLen() + 2),fn join(xs: String[], sep: String = ", ", last: String = sep). One default is evaluated where the call is written:Location.caller(), the position of that call, as the default value of a parameter or of a field, which the construction of the record fills (8.1). Core and generated code write it,#Errorfor instance; written anywhere but in a default value, it is an error. On a generic function, the default value is computed for the instance called,fn first<T>(xs: T[], fallback: T = xs[0]), and is not used to deduce the types of the call. - Variadic parameters. The last parameter can receive the extra arguments of the call:
fn sum(xs: Int...): Intsees it as anInt[], andsum(1, 2, 3)fills it,sum()leaves it empty.sum(xs...)passes it an array as is, without copying it, as doessum(xs: ys); neither mixes with extra arguments. The element type is deduced for a generic function,fn largest<T: Ord>(first: T, rest: T...): T. The parameter is received read-only, assinkor aslazy, without a default value: a variadic parameter is only an array written more lightly, andlazy xs: Int...builds the array of the extra arguments only if the function reads it (6.6). A function value,::sum, receives the array,(Int[]) => Int. A variadic C function is written differently,...without a type (9). - Forms of a method. A function of an
impl, generic or not, or a free function, can have several forms, distinguished by the names of their parameters:fn in(self, zone: TimeZone): Zoned ! ResolveErrorandfn in(self, zone: TimeZone, resolve: Resolve): Zoned. Each has its own signature, its result included; the call chooses the only one that takes its arguments, positional then named, its parameters without default value all filled. Two forms with the same names, or a call that several take, are compile errors:no form of `Z.at` takes these arguments: `at(k:)`, `at(k:by:)`. Taken as a value,::sorZoned::plus, the function designates the form that the expected type calls for, the one that has its number and types of parameters. - Overloading, in practice. Weaver does not choose a function by the types of its arguments:
::f, a lambda passed as an argument and inference would no longer have a unique target. What overloading is used for elsewhere is written differently:- forms, which differ by the names of their parameters,
at(k)andat(k, by: 2); a contract does not declare any, a method having one name in it, but animpl Xadds a form to the method of an adoption,LocalDate.parse(s, format)alongsideLocalDate.parse(s); - default parameters,
read(mut buf, from: Int = 0); - a constrained generic, which accepts any type adopting a contract:
fn read<P: AsPath>(path: P)receives aPathor a string, and a program type joins in by adoptingAsPath; - operators, the only place where types choose: a symbol is bound to several functions, one per pair of operand types (4), generic ones included, the non-generic function winning:
@operator("+") fn plusShow<T: Show>(s: String, x: T): String = s + "${x}"@operator("+") fn plusInt(s: String, n: Int): String = s + "#${n}""p = " + Point{x: 1, y: 2} // plusShow: "p = Point{x: 1, y: 2}""n = " + 3 // plusInt, more specific: "n = #3"
- forms, which differ by the names of their parameters,
3.2 Loops and ranges
Section titled “3.2 Loops and ranges”- Three loops.
for x in seq,while condandloop. There is no C-stylefor: ranges with a step replace it. - Exits.
breakandcontinue, with an optional label ('lines: for …,continue 'lines).loopis an expression:break valueexits it with a result, and only aloopcan do so. Labeled, it still can:val v = 'search: loop { … break 'search x }, whosebreakexits inner loops. Aloopwithoutbreakdoes not terminate: it is Never. - Ranges.
a..bis exclusive,a..=binclusive,a..open. A range is aRangevalue usable outside loops. An Int range with a step,0..n step 2, or open,1.., is a sequence, a coreStepped:(0..n step 2).map(…),zip(xs.seq(), 1..); likewise0..nwhere a sequence is expected, the argument ofzip. Its last element never overflows an Int, andfor i in 0..ends only bybreak. Open, a range of another integer or of characters goes up to the largest element of its type:for b in x..on a UInt8 ends at 255. - Step.
stepsets a positive or negative step, 1 by default. The bounds are of the same type: an integer of any size, a character, or a floating-point number; a literal takes the type of the other bound,0..non an Int16. The step of a floating-point range is of their type; that of the others is an Int, a displacement rather than a value of the type, so that a UInt8 can go down:for i in n..=0 step -1. Each element isa + i × step: no accumulated error on floats. A zero step is a compile error if it is constant, a panic otherwise. A range traversed in the wrong direction is empty. An element that would fall outside the type of the bounds does not exist: the loop stops, without overflow, and0..=255on a UInt8 makes 256 iterations.'a'..='z'iterates over characters, skipping surrogates, which are not characters. - Iterating over an array.
for x in xsiterates over the value ofxsat the start of the loop. The body may modifyxs: the loop sees none of it (6.1).for mut x in xsmodifies each element in place,xsbeing a variable: it is lent to x for the duration of the loop (6.3), which uses it in no other way, so that its size does not change;for mut (n, s) in xslikewise modifies each part of a tuple. A fixed array is iterated likewise. The pattern of aformatches each element: a tuple destructures it, butfor Some(x) in os, which would silently skip elements, is rejected; one writesfor o in os { if o is Some(x) { … } }, orfor x in os.flatten(). - Iterators. A type that adopts
Iterable<T>,fn next(mut self): T?, is iterated byfor: each iteration callsnext, and the loop stops onNone. The loop advances on its own copy: the iterated variable does not move, except an iterator that holds resources, which the loop takes over and disposes of, the variable being consumed. An array lends its elements to the loop, as does a collection iterated throughiter, whose iterator borrows its storage, alocal type, and whosenextlends,yield T? from …(memory-model.md, section 9):for (k, v) in mcopies neither the table nor its entries, and a value kept beyond its turn is written.copy(). A generator gives up what it creates, and resources are then adopted byfor using x in …(7.1).for (k, mut v) in mmodifies each value of a Map in place, the loop using m in no other way: a collection modifiable so declares an iterating projection,property each(mut self): (K, mut V), whose body walks its storage and yields each element in turn,yield (e.key, &e.value); the loop’s body runs at eachyield(6.3), the loop findingeachby its name: no contract says which parts of aTare places, and generic code modifies no collection in place. Its result type marks withmutthe parts yielded as places,(K, mut V): amutbinding of another part, the key, is refused.for chunk in data.utf8Chunks()thus splits on demand, without building an array. A collection that is not an iterator provides one: it adoptsTraversable<T, I>,fn iter(self): IwhereI: Iterable<T>, andfor x in viterates overv.iter(), without v moving. Map, OrderedMap and Set adopt it; a boundC: Traversable<T, I>also constrains I, and the body iterates over c withfor. - Several variables. The loop
for (i = 0, j = n; i < j; i++, j--)is written withzip. More complex cases go throughwhile.
for i in 0..n step 2 { ... } // 0, 2, 4… while < nfor i in 10..=0 step -2 { ... } // 10, 8, 6, 4, 2, 0for x in 0.0..1.0 step 0.25 { ... } // 0, 0.25, 0.5, 0.75for (i, j) in zip(0..n, n - 1..=0 step -1) { ... }
'lines: for row in grid { for cell in row { if cell.isEmpty() { continue 'lines } }}
val first = loop { val l = r.readLine()! if !l.isBlank() { break l }}Ranges are also used in patterns, without step: Some(0xC2..=0xDF). Their bounds fit in the matched type. A match on an integer or a character is exhaustive when its literals and ranges cover the whole type, 0..=127 and 128..=255 on a UInt8, a UInt64 beyond 2^63 included; surrogates not being Chars, '\0'..='\u{D7FF}' and '\u{E000}'..='\u{10FFFF}' cover all characters. Otherwise the compiler names what is missing, 100..=255 or 'b', or _ for the tail of a type of 32 bits or more.
3.3 Pattern tests
Section titled “3.3 Pattern tests”x is Patternis a boolean expression. The variables it binds are visible in the rest of a&&chain and in theifblock, but neither in theelsenor after a||.val Pattern = expr else { … }binds the variables for the rest of the block. Theelseblock must exit it (return,break,continueor panic).while x is Patternrepeats the body as long as the pattern matches; its variables are visible in the body.- Membership.
in rmatches a value that r contains, viar.contains(x):in 'a'..='z' => …,in vowels => …on a Set,x is in nameson an array. Aninarm does not count toward exhaustiveness.x is rwould bind a new namerand always succeed: when that name shadows a variable, the compiler warns and suggestsis in r. - Guards.
Pattern if conditionretains the arm only if the condition is true, inmatchas incatch. A guarded arm does not count toward exhaustiveness. The bindings of anisin the guard hold in the arm, as in the block of anif:Word(s) if next is Some(n) => "${s}${n}". - Alternatives.
A(n) | B(n) => n: each alternative binds the same names, with the same types, and the arm reads them without knowing which one matched the value. A name bound in only one alternative, or with two types, is an error. Amutorusingbinding is allowed if each alternative binds it the same way:Circle(mut r) | Square(mut r) => r += 1. - Implicit variant.
.arraymatches the variant of that name of the matched type, without repeating it, at any level of a pattern:Some(.array) => …; likewiseSome(.object)in an expression takes its type from the other operand,top != Some(.object). - Variant patterns. They name each field, by position or by name:
Rect(w, _),Rect(h: x, w: _). An omitted field is an error, which makes a field added to a variant a change visible at everymatch. A range0..10excludes its upper bound,0..=9includes it; open, it goes to the end of the type,10..up to the largest element,..0and..=9from the smallest, and counts toward exhaustiveness:..0 => …,0..10 => …,10.. => …cover an Int. - On a type parameter. In
fn f<E>(e: E),e is Cancelledormatch e { Circle(_) => …, _ => … }matches the variant of a visible enum, named alone or qualified, its fields as_: the pattern binds nothing. The body is checked once, E unknown; each instance decides the pattern, true if E is the variant’s enum, false if it cannot be, and a tag test if E is a union that contains it,IoError | Cancelled. Such an arm does not count toward exhaustiveness. This is how a pool silences theCancelledof its daemons, whatever their error type. - Record patterns.
Response{status: 200..=299, body, ..}matches a record by its fields, each one named:name: pattern, ornamealone, which binds the field under its name. Without.., the pattern names each field, like those of a variant, and an added field shows up at every pattern;..leaves the others. The brace is attached to the type name, like that of a literal:x is Red {opens the block that follows. The name is resolved like that of a literal,fs.Metadata{kind, ..}, and must designate the type of the matched value. It counts toward exhaustiveness like the tuple of its fields, at any level of a pattern,Ok(Response{status: 200..=299, body, ..}), and destructures a record in avalor aforwhen it cannot fail,val Point{x, y} = p. A field hidden from the module cannot be named in it. - Tuples and strings.
(a, b)matches a tuple element by element,match (x.negative, y.negative) { (false, true) => … }, and counts toward exhaustiveness like a single variant. A string literal matches a string:"" | "k" | "K" => 1 << 10; only_covers them all. usingbinding. A value that comes from a call is given up by it (7.1): if it carries a resource, the pattern adopts it byusing x,while files.pop() is Some(using f), and the binding answers for it like ausingbinding: it gives it up, or disposes of it at the end of the block. Withoutusing, it is an error, as isusing xon a lent value, a variable or an element. A_cannot lose a given-up resource, nor can anisthat fails:files.pop() is Nonewould lose that of aSome.mutbinding.Pattern(mut x)bindsxwith exclusive access when the matched value is modifiable (var,val … = mut,using,mutparameter, or one of their fields or elements): modifyingxmodifies the matched value in place. The rules of 6.2 apply: as long asxlives (the arm, theifblock, the rest of the block of aval … else), the matched variable is used only through it. Exclusive access applies to the matched path: duringif t.counter is Count(mut n),t.totalremains free, two distinct fields each being modified on their own;t.counter,tas a whole, or a path through an index, are used only throughn. Acatchmatches an error, which is not modifiable: nomutbinding.
if info is Some(m) && m.isFile() { c.bytes = m.size() }
val Some(user) = cache.get(id) else { fail NotFound(id) }
while heap.pop() is Some(head) { emit(head) }
match sep { Some(t) if t.byteLen() == 1 => Some(t.byte(0)) Some(t) => fail Usage("multi-character tab '${t}'") None => None}
fn next(r: mut Run): Bytes? ! IoError = match r { Memory(mut lines) => lines.next() Spilled(mut reader) => reader.readLine()}