You will use
- List patterns:
[],[only],[first, second],[first, ..rest] pooka/list:list.lengthandlist.each
The whole program
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
- Patterns describe shapes.
[]is an empty list.[only]is exactly one element.[first, second]is exactly two. ..restmeans "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.- 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.