Skip to content
Weaverv0.5.0

Functions, control and pipelines

Everything is an expression, every function can be called like a method, and lazy sequences are fused at compile time.

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. An if, a match or 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 be mut: (mut Int[]) => () receives a location, which the call designates by f(&xs); a lambda expected under this type modifies its parameter in place, xs => xs.push(1).
  • Uniform call. x.f(y) is equivalent to f(x, y). Every free function becomes an extension method, with no extra declaration.
  • Pipeline. a |> f(b) is equivalent to a.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 as f(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. ::isBlank passes a declared function, Char::isAsciiDigit a 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) means x => f(a, x, c), and cmp.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 as mut makes 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 extends Iterable<T>, whose methods map, filter, flatMap, take, skip, takeWhile, skipWhile, enumerated, zip, chain return adapters, and collect, fold, forEach, count, first, any, all traverse 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 through impl Seq<T> for X {}. weaver.seq has zip(a, b) and iterate(x, f); weaver.collections has groupBy, 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 read total elsewhere. An enclosing lambda that captures it also takes it by [var total].
    • [take file] () => file.write(r)!: the closure becomes the owner, like sink, and file is 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 mut closure 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 as sink: 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 a fail in the body makes it a T ! E, the error being the union of what they propagate: () => "${f()!}". Where () => T ! E is 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), call connect(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, self included. 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, #Error for 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...): Int sees it as an Int[], and sum(1, 2, 3) fills it, sum() leaves it empty. sum(xs...) passes it an array as is, without copying it, as does sum(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, as sink or as lazy, without a default value: a variadic parameter is only an array written more lightly, and lazy 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 ! ResolveError and fn 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, ::s or Zoned::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) and at(k, by: 2); a contract does not declare any, a method having one name in it, but an impl X adds a form to the method of an adoption, LocalDate.parse(s, format) alongside LocalDate.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 a Path or a string, and a program type joins in by adopting AsPath;
    • 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"
  • Three loops. for x in seq, while cond and loop. There is no C-style for: ranges with a step replace it.
  • Exits. break and continue, with an optional label ('lines: for …, continue 'lines). loop is an expression: break value exits it with a result, and only a loop can do so. Labeled, it still can: val v = 'search: loop { … break 'search x }, whose break exits inner loops. A loop without break does not terminate: it is Never.
  • Ranges. a..b is exclusive, a..=b inclusive, a.. open. A range is a Range value usable outside loops. An Int range with a step, 0..n step 2, or open, 1.., is a sequence, a core Stepped: (0..n step 2).map(…), zip(xs.seq(), 1..); likewise 0..n where a sequence is expected, the argument of zip. Its last element never overflows an Int, and for i in 0.. ends only by break. 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. step sets 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..n on 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 is a + 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, and 0..=255 on a UInt8 makes 256 iterations. 'a'..='z' iterates over characters, skipping surrogates, which are not characters.
  • Iterating over an array. for x in xs iterates over the value of xs at the start of the loop. The body may modify xs: the loop sees none of it (6.1). for mut x in xs modifies each element in place, xs being 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 xs likewise modifies each part of a tuple. A fixed array is iterated likewise. The pattern of a for matches each element: a tuple destructures it, but for Some(x) in os, which would silently skip elements, is rejected; one writes for o in os { if o is Some(x) { … } }, or for x in os.flatten().
  • Iterators. A type that adopts Iterable<T>, fn next(mut self): T?, is iterated by for: each iteration calls next, and the loop stops on None. 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 through iter, whose iterator borrows its storage, a local type, and whose next lends, yield T? from … (memory-model.md, section 9): for (k, v) in m copies 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 by for using x in … (7.1). for (k, mut v) in m modifies 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 each yield (6.3), the loop finding each by its name: no contract says which parts of a T are places, and generic code modifies no collection in place. Its result type marks with mut the parts yielded as places, (K, mut V): a mut binding 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 adopts Traversable<T, I>, fn iter(self): I where I: Iterable<T>, and for x in v iterates over v.iter(), without v moving. Map, OrderedMap and Set adopt it; a bound C: Traversable<T, I> also constrains I, and the body iterates over c with for.
  • Several variables. The loop for (i = 0, j = n; i < j; i++, j--) is written with zip. More complex cases go through while.
for i in 0..n step 2 { ... } // 0, 2, 4… while < n
for i in 10..=0 step -2 { ... } // 10, 8, 6, 4, 2, 0
for x in 0.0..1.0 step 0.25 { ... } // 0, 0.25, 0.5, 0.75
for (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.

  • x is Pattern is a boolean expression. The variables it binds are visible in the rest of a && chain and in the if block, but neither in the else nor after a ||.
  • val Pattern = expr else { … } binds the variables for the rest of the block. The else block must exit it (return, break, continue or panic).
  • while x is Pattern repeats the body as long as the pattern matches; its variables are visible in the body.
  • Membership. in r matches a value that r contains, via r.contains(x): in 'a'..='z' => …, in vowels => … on a Set, x is in names on an array. An in arm does not count toward exhaustiveness. x is r would bind a new name r and always succeed: when that name shadows a variable, the compiler warns and suggests is in r.
  • Guards. Pattern if condition retains the arm only if the condition is true, in match as in catch. A guarded arm does not count toward exhaustiveness. The bindings of an is in the guard hold in the arm, as in the block of an if: 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. A mut or using binding is allowed if each alternative binds it the same way: Circle(mut r) | Square(mut r) => r += 1.
  • Implicit variant. .array matches the variant of that name of the matched type, without repeating it, at any level of a pattern: Some(.array) => …; likewise Some(.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 every match. A range 0..10 excludes its upper bound, 0..=9 includes it; open, it goes to the end of the type, 10.. up to the largest element, ..0 and ..=9 from 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 Cancelled or match 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 the Cancelled of its daemons, whatever their error type.
  • Record patterns. Response{status: 200..=299, body, ..} matches a record by its fields, each one named: name: pattern, or name alone, 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 a val or a for when 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.
  • using binding. A value that comes from a call is given up by it (7.1): if it carries a resource, the pattern adopts it by using x, while files.pop() is Some(using f), and the binding answers for it like a using binding: it gives it up, or disposes of it at the end of the block. Without using, it is an error, as is using x on a lent value, a variable or an element. A _ cannot lose a given-up resource, nor can an is that fails: files.pop() is None would lose that of a Some.
  • mut binding. Pattern(mut x) binds x with exclusive access when the matched value is modifiable (var, val … = mut, using, mut parameter, or one of their fields or elements): modifying x modifies the matched value in place. The rules of 6.2 apply: as long as x lives (the arm, the if block, the rest of the block of a val … else), the matched variable is used only through it. Exclusive access applies to the matched path: during if t.counter is Count(mut n), t.total remains free, two distinct fields each being modified on their own; t.counter, t as a whole, or a path through an index, are used only through n. A catch matches an error, which is not modifiable: no mut binding.
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()
}