Skip to content

Functions & Lambdas

A function is a named piece of code. A lambda is a function without a name. Both are called the same way and take the same kinds of parameters. Either one can go into a pipe or be passed to another function.

fn add(x: Int, y: Int) -> Int
    x + y
end

fn abs(x: Int) -> Int
    if x < 0 then return -x
    x
end

fn main()
    dbg add(3, 4)
    dbg abs(-9)
end

The last expression is the return value. Use return only to leave early, as abs does for a negative number.

Every parameter must be read in the body. If a parameter is unused on purpose, name it _ or start its name with _, as in fn constant(_input: Int) -> Int.

fn main()
    inc = fn x: Int -> x + 1
    dbg inc(41)

    describe = fn name: String, count: Int ->
        noun = if count == 1 then "item" else "items"
        "${name}: ${count} ${noun}"
    end

    dbg describe("cart", 3)
end

A lambda is written fn params -> body. Several parameters are separated by commas. A body of more than one line goes on the lines below the ->, closed by end, as describe’s does.

Write a parameter’s type when nothing else tells the compiler what it is, as for a lambda bound to a name. A lambda passed to a function that expects a certain type gets its parameter types from there. In a list of lambdas, writing the type in one element is enough: [("a", fn n: Int -> n), ("b", fn n -> n * 2)].

A lambda is a value. You can bind it to a name, pass it to a function, or return it from one.

Named functions are values too. After f = add, the call f(3, 4) works the same as add(3, 4).

struct Point
    x: Int
    y: Int
end

fn main()
    xs = [1, 2, 3]
    dbg xs |> Iter.filter(&(&1 > 1)) |> Iter.to_list()
    dbg xs |> Iter.map(&(&1 * 2 + 1)) |> Iter.to_list()
    dbg xs |> Iter.map(&Point{x: &1, y: 0}) |> Iter.to_list()
    dbg xs |> Iter.map(&Int.max(&1, 2)) |> Iter.to_list()
    dbg xs |> Iter.map(&"id ${&1}") |> Iter.to_list()
end

A capture writes a small function in place: &, then the function’s body. &1 is its first parameter, &2 its second. &(&1 > 1) is fn n -> n > 1, &Point{x: &1, y: 0} is fn n -> Point{x: n, y: 0}, and &"id ${&1}" is fn n -> "id ${n}".

Iter.filter and Iter.map work on any collection, and Iter.to_list collects the result into a list. Collections covers them.

The body after & is a call, a literal, or an expression in parentheses, so &(&1 > 1) needs its parentheses. A capture that only passes &1 on to a call is a partial application: at_least_zero = &Int.max(&1, 0) keeps Int.max’s parameter types, so it needs no annotation. Write a lambda when the body takes more than one step or needs names.

Fine print

  • The body after & is one operand, so &f(&1) + 1 adds 1 to a capture. The function of the sum is &(f(&1) + 1).
  • Captures don’t nest: &f(&1, &g(&1)) is an error that asks for the inner one as a lambda.
  • Any capture other than a partial application needs a function type from its position. f = &(&1 > 2) alone is cannot infer type for `&1` in `&(&1 > 2)` .
  • A partial application keeps the callee’s parameter names and defaults, so it takes named arguments.
  • _ is not a placeholder: add(1, _) is an error whose help writes &add(1, &1).
fn connect(host: String, port: Int = 8080, timeout: Int = 30) -> String
    "${host}:${port}/${timeout}"
end

fn main()
    c = &connect(&1, port: &2)
    dbg c(port: 80, host: "x") // "x:80/30"
    dbg c("y")                 // "y:8080/30"
end

Spec: Captures, Parameters and their types.

Two functions in the same scope can’t have the same name. Nomi never picks between functions by the types of the arguments, so this is an error. (type UserId String declares a distinct type, which Structs, Enums, Distinct Types covers.)

type UserId String

fn parse(_text: String) -> Int
    0
end

fn parse(_id: UserId) -> Int
    0
end

fn main()
    Unit
end

Give each function a name that says what it does, as the standard library does: String.to_int(text), Date.parse(text), Date.new(year, month, day).

When you want one operation that works on several types, define an interface and implement it for each type. The call names the type or the interface, so it is always clear which version runs.

fn greet(name: String, greeting = "Hello") -> String
    "${greeting}, ${name}!"
end

fn main()
    dbg greet("World")
    dbg greet("World", "Hi")

    // Lambdas take defaults the same way:
    add = fn x: Int, y = 10 -> x + y
    dbg add(5)
    dbg add(5, 2)
end

A parameter can have a default value. A caller can leave that argument out, or pass a value to replace the default.

A parameter with a default can leave its type off when the default says it: greeting = "Hello" makes greeting a String, and the lambda’s y = 10 makes y an Int. An empty list or None says no type, so a parameter with one of those as its default keeps the type written.

Passed to a function such as Iter.map, greet still fills greeting from its default: ["Ada", "Lin"] |> Iter.map(greet) greets each name with "Hello".

Fine print

  • A default runs on each call that leaves its argument out, after the written arguments. It may read earlier parameters: fn area(width: Int, height: Int = width).
  • Positional arguments can’t skip a default in the middle. For fn middle(a: Int, b: Int = 10, c: Int), middle(1, 2) is a missing argument for c; write middle(1, c: 2).
  • Defaults belong to the function’s name and the local names that copy it: after g = greet, g("World") fills the rest, as it does for a lambda bound to a name. A function passed to another one, or kept in a list or a field, is called with every argument.
  • ? and return can’t stand directly in a default. It has no function to return from.

Spec: Default Arguments.

fn connect(host: String, port: Int = 8080, timeout: Int = 30) -> String
    "${host}:${port}:${timeout}"
end

fn main()
    dbg connect("localhost")
    dbg connect("localhost", timeout: 10)
    dbg connect(host: "api", port: 443, timeout: 5)
end

You can pass any argument by name, as timeout: 10. Named arguments can come in any order. When you mix the two kinds, positional arguments come first.

Names help most with defaults. The second call sets timeout and keeps the default port without writing it.

Fine print

  • Naming a parameter that already has a value, by position or by an earlier name, is parameter 'port' already has a value.
  • Only a declared function, or a lambda or partial application bound to a name, has parameter names. A parameter or field of function type has none: f("a", port: 1) through one is no parameter named 'port'.
  • A variant’s payload is positional: Some(value: 1) is an error.

Spec: Named Arguments.

type Dur Int

struct Point
    x: Int
    y: Int
end

fn subtract(Dur(a), Dur(b)) -> Dur
    Dur(a - b)
end

fn sum_point(Point{x:, y:}) -> Int
    x + y
end

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

fn main()
    Dur(diff) = subtract(Dur(10), Dur(3))
    dbg diff
    dbg sum_point(Point{x: 4, y: 5})
    dbg add_pair((20, 22))
end

A parameter can be a pattern instead of a plain name. The pattern unpacks the argument as the function is called. sum_point gets the x and y fields of its Point directly.

The pattern must match every possible value of its type. Patterns like that are called irrefutable. Tuples, structs, distinct types such as Dur, and enums with one variant all qualify.

When the pattern names a type, as Dur(a) and Point{x:, y:} do, you don’t write the type again. A tuple or an anonymous struct pattern names no type, so it needs one, as in (a, b): (Int, Int).

A type name with nothing after it is a pattern too. It names the type and binds nothing, so fn health(Request) -> Response takes a Request it never reads.

Fine print

  • A pattern that can fail is refutable pattern in parameter; bind the parameter and use a `case` in the body. That covers literals, a variant of an enum with more than one, and any list, map, vector or set pattern.
  • A type name alone must name a type, not a variant: fn f(None) is parameter 'None' needs a name.
  • Lambdas take the same patterns: fn (_, n) -> n.

Spec: Parameter Destructuring.

fn transform(x: Int, factor: Int = 1, f: (Int) -> Int) -> Int
    f(x * factor)
end

fn double(n: Int) -> Int
    n * 2
end

fn main()
    dbg transform(5, fn x -> x + 1)
    dbg transform(5, factor: 3, fn x -> x + 1)
    dbg transform(5, factor: 3, double)
end

A callback is a function you pass to another function. When a function’s last parameter is a function, you can pass that argument last without a name. In transform(5, fn x -> x + 1), the lambda skips factor and goes to f, so factor keeps its default. The same happens after a named argument, as in the second call.

The last call passes double, an existing function, instead of a lambda. It goes to f the same way. What decides is the parameter list, not how the argument is written.

This happens only when the last parameter takes a function and the skipped one does not. When both take functions, the arguments fill the parameters in order.

struct Header
    title: String
end

fn parse(text: String) -> Header
    todo "parse the header"
end

fn main()
    dbg parse("# Notes")
end

todo marks a body or a value you haven’t written yet. It fits any type, so the rest of the program still checks and runs.

If the program reaches it, the program stops with todo reached at main.nomi:6: parse the header. The editor shows each todo as a warning, and nomi build refuses a program that still has one.

todo is still free as a name: fn apply(todo: Todo) works, and inside it a bare todo reads the parameter. Write the placeholder with a reason there.

fn first_field(line: String) -> String
    case String.split(line, ",") |> Iter.first()
        Some(field) -> field
        None        -> unreachable "split always returns at least one part"
    end
end

fn main()
    dbg first_field("a,b")
    dbg first_field("")
end

unreachable marks a place your own code guarantees it never gets to, and its reason says why. Like todo, it fits any type. Unlike todo, it is finished code: nomi build accepts it.

If the program does reach it, the guarantee was wrong, so the program stops with line 4: unreachable: split always returns at least one part. Use it only for what the program itself makes true, as here: String.split never returns an empty list. Input a user typed makes no such promise, so a missing value there needs real handling.

When the guarantee is that one call succeeds, a postfix ! says it after the call: Date.new(2024, 1, 1)!. Keep unreachable for a reason the reader cannot see from the call, like the one above.

Fine print

  • The reason is required and is a plain string literal. A bare unreachable is `unreachable` needs a reason.
  • It counts as an exit: a statement after it is unreachable code after `unreachable` .
  • It traps in every build, and the compiler never optimizes on it.
  • todo is different: as a statement it is Unit, so code after it stays legal, and a body holding one may leave its parameters unread.

Spec: Unreachable code, Unwritten code.

Every example that uses Functions & Lambdas

Pipes is next. It shows how |> joins these calls into code that reads from top to bottom.