← Cookbook Basics Beginner · Pooka 0.5.0

Match on the shape of a list

A list is empty, has one thing, two things, or a first thing and the rest. match can tell them apart without counting.

You will use

  • List patterns: [], [only], [first, second], [first, ..rest]
  • pooka/list: list.length and list.each

The whole program

src/main.pooka
module main

import pooka/int
import pooka/io
import pooka/list

describe(guests: List(String)) -> String {
  match guests {
    [] -> "Nobody came. More tea for us."
    [only] -> only + " came alone."
    [first, second] -> first + " and " + second + " came together."
    [first, ..rest] -> first + " came with " + int.to_string(
      list.length(rest)
    ) + " friends."
  }
}

main() {
  [[], ["Ada"], ["Ada", "Bo"], ["Ada", "Bo", "Cy", "Di"]]
  |> list.each(fn(guests: List(String)) {
    io.println(describe(guests))
    Nil
  })
}

Run it

$ pooka run
Nobody came. More tea for us.
Ada came alone.
Ada and Bo came together.
Ada came with 3 friends.

How it works

  1. Patterns describe shapes. [] is an empty list. [only] is exactly one element. [first, second] is exactly two.
  2. ..rest means "and the others". [first, ..rest] matches any list with at least one element and names the remainder. It comes last, because it would also match the shorter shapes above it.
  3. Every shape is covered. Remove the last arm and the compiler refuses, naming the shape you forgot: help: Handle `[_, _, _, ..]` or add a fallback branch.

Try next: patterns nest. ["Ada", ..] matches any list that starts with Ada, and [#(name, age), ..rest] takes apart a list of tuples.