Skip to content

Calls and functions

When a function call’s result is an argument to another function call, write it as a |> pipe chain instead of nesting (spec §8 Pipes; tour: Pipes):

// no
Iter.to_set(Iter.map(s, f))

// yes
s
|> Iter.map(f)
|> Iter.to_set()

A constructor is a function call like any other, so a constructor whose argument is another call is a nested call too:

// no
MeteredReader.new(Reader.from_text("hello"))

// yes
"hello" |> Reader.from_text() |> MeteredReader.new()

The same goes for Seed.from_int(42) |> Factory.new() and Reactor.new() |> Reactor.input("input", 1).

Every stage is a call, so a stage keeps its parentheses even when nothing else goes in them: |> Iter.to_list(), |> io.print(). Reach for |> then fn v -> ... for a small step no named function covers; once the step has a name worth giving, write the function and call it.

Let the pipeline subject lead. When a value is the subject flowing through several operations, put it on its own first line and align every |> with it, even when the subject is a bare name:

s
|> Set.size()
|> io.print()

Inline is still fine for a short expression where the call itself is the point: Set.size(s) |> io.print(). Prefer the stacked form once the chain is doing real pipeline work, when a lambda makes a stage multi-line, or when starting from the subject makes the data flow easier to scan.

Lift a composite-literal seed to its own stage. When the innermost subject is a composite literal (a list, map, set, tuple or struct literal), give it its own seed stage so the pipeline visibly starts from the data:

// no: the data is buried inside the first call
Iter.to_set([1, 2, 3])
|> Set.size()
|> io.print()

// yes: the list literal seeds the chain
[1, 2, 3]
|> Iter.to_set()
|> Set.size()
|> io.print()

Don’t pipe when there’s no nested call:

  • A plain value or literal argument stays a direct call: Int.to_string(n), Iter.count(s). A lone call is never a pipe.
  • A composite literal also stays direct when there is only one operation and the call is the whole expression: Iter.reduce([1, 2, 3], 0, fn acc, n -> acc + n).
  • A nested call that is not the first argument stays nested: Map.put(m, k, compute(v)), Cipher.decode(cipher, Cipher.encode(cipher, plaintext)). compute(v) is a value being stored, not the pipeline subject. Reach for |> then &f(a, &1) only when the nested call is the subject and its value goes elsewhere than the first argument.
  • A recursive call with several arguments may keep a nested first argument too, so that its arguments line up with the parameters they replace: search(Iter.to_list(next), Set.union(seen, next), moves + 1, sizes, goal).
  • A short nested call inside a literal stays nested: (Reverse.of(Standing.points(s)), s.team), not (Standing.points(s) |> Reverse.of(), s.team). A pipe reads well as a literal’s whole field value, not as one short element among others.

Operators and fields:

  • A |> chain can feed equality or ordering directly: xs |> Iter.to_list() == [1, 2, 3].
  • A |> chain can be an operand of and or or directly: Iter.is_empty(run) or Iter.windows(list, Iter.count(run)) |> Iter.any_match(&(&1 == run)). Don’t bind it first: a binding runs the chain even when the other operand already decides the result, and the operator would not.
  • For arithmetic, concatenation and other expression-building operators, bind the pipeline first (inner = xs |> Iter.map(Int.to_string) |> Iter.to_list()), then build the expression from the binding.
  • Pipes work in place inside struct and enum literal fields (Foo{v: x |> g() |> h()}), so don’t extract a binding just to pipe a field value.

End a fallible stage with ?. Write the ? right after the stage whose failure it passes up, so each stage reads as one step:

order =
    text
    |> parse()?
    |> validate()?

When a then lambda’s result is what can fail, write then?. A ? at the end of the lambda’s body exits the lambda, not the function:

port =
    text
    |> String.trim()
    |> then? fn t -> parse_port(t, config)

Reach for dbg (spec §8 dbg; tour: Pipes) for temporary tracing. It returns its value, so it goes inside an expression (total = dbg subtotal + tax) or as a pipe stage (|> dbg) without restructuring the code. Keep io.inspect(value) for intentional program output where a Debug rendering is part of the program’s behavior.

dbg, tap or then. The three stages serve different needs (spec §8 The tap stage):

  • |> dbg is a temporary look at the value. It is a warning in the editor and nomi build refuses it, so it never ships.
  • |> tap fn v -> ... is an effect the program keeps, such as a log line or a progress message, run on the value without changing it. Its lambda returns Unit. A function that takes the value as it is goes by name, |> tap log_line, not |> tap &log_line(&1).
  • |> then fn v -> ... replaces the value with the lambda’s result.
command =
    input
    |> String.words()
    |> tap fn words -> log.debug("got ${Iter.count(words)} words")
    |> parse_command()

Do not use tap to hide work that computes something: if the lambda’s result matters, it is a then stage or a named function.

Every call is qualified (spec §8 Calls and qualification; tour: Interfaces & Dispatch). An interface function can be called through its type, its interface or a bounded type parameter (Int.to_string(n), Display.to_string(x), T.to_string(x)); pick the qualifier that says the most. When the value’s type is known, call through the type: Date.year(on), not DateParts.year(on). Name the interface when the contract is the useful thing to name, or when two interfaces share a function name on the same type.

Inside an impl block, call a sibling function of the same block bare:

impl Speech for Dog
    fn speak(d: Dog) -> String
        "${d.name} says woof"
    end

    fn shout(d: Dog) -> String
        speak(d) + "!"
    end
end

io.print takes any Display value; don’t pre-stringify. It dispatches Display.to_string itself (the same path ${...} interpolation uses), so write x |> io.print() or io.print(x), not x |> Int.to_string() |> io.print() and not io.print("${x}"), a string that is one interpolation and nothing else. Interpolate when the line has text around the value ("total: ${x}"). That includes a value whose static type is the Display interface itself: io.print(v) and "${v}" render it through the value’s own impl. The one case that stringifies before printing is feeding + concatenation (io.print("n=" + Int.to_string(n)), which needs a String). io.inspect(x) is the parallel shorthand for the Debug rendering and returns Unit. Use dbg (§8) to inspect a value without breaking an expression or pipeline.

10. Read a field with .name, not fn x -> x.name

Section titled “10. Read a field with .name, not fn x -> x.name”

Where a function only reads a field, pass the field accessor (spec §7 Field Accessors; tour: Structs, Enums & Distinct Types). It says the one thing the lambda says, without a parameter name to invent:

names = users |> Iter.map(.name) |> Iter.to_list()

youngest_first = Iter.sort_by(users, .age)

cities = users |> Iter.map(.address.city) |> Iter.to_list()

Keep the lambda when its body does more than read fields: a computation (fn u -> u.age + 1), a call (fn u -> String.uppercase(u.name)), or a condition (fn u -> u.age > 18). Don’t pipe into an accessor; read the field from the value: user.name, not user |> .name.

A tuple’s items are read the same way, .first and .second, when the tuple was built a line or two above, where the reader can see what each part is:

message |> Iter.zip(zigzag(rails)) |> Iter.sort_by(.second) |> Iter.map(.first)

When the tuple was built far from where it is read, such as in another function or a once, take it apart in the lambda instead, so the names say what the parts are: Iter.map(roster, fn (name, _grade) -> name).

11. Pass a constructor, not fn x -> Some(x)

Section titled “11. Pass a constructor, not fn x -> Some(x)”

Where a function only wraps its argument, pass the constructor itself (spec §7 Constructors as Function Values; tour: Structs, Enums & Distinct Types): a positional variant (Some, Ok, Shape.Circle) or a distinct type that wraps a value (Id for type Id Int). The lambda says the same thing with a parameter name to invent:

ids = rows |> Iter.map(.id) |> Iter.map(UserId) |> Iter.to_list()

somes: List<Maybe<Int>> = Iter.map(ns, Some) |> Iter.to_list()

labelled = Result.map_err(result, ParseError)

Keep the lambda when it does more than wrap: a computation inside the constructor (fn n -> Id(n + 1)), a struct-shaped variant, which has no function value (fn w -> Shape.Rect{w:, h: w}), or a positional variant over a tuple whose parts arrive as separate arguments.

A block’s last expression is its value, so a function or lambda ends with the value, not return value (spec §7 Returning). Keep return for an exit before the end:

fn clamp(n: Int) -> Int
    if n < 0 then return 0
    if n > 100 then return 100
    n
end

A run of guards like these keeps the main path unindented, where an if/else would nest it. A body you have not written yet gets todo, not a bare return (§30).