5. Lists, tuples and destructuring
The built-in List has literals, ++ for concatenation, len, range and for-in.
List patterns destructure head and tail:
fn describe(xs: List[Int]) -> String =
match xs {
[] -> "empty"
[x] -> "just $x"
[first, ..rest] -> "$first, and ${len(rest)} more"
}
pub fn main() -> Unit !io = {
println(describe([]))
println(describe([9]))
println(describe([1, 2, 3]))
}
Open in playground
empty
just 9
1, and 2 more
A tuple packs a fixed number of values of different types; let destructures one
directly:
fn divmod(a: Int, b: Int) -> (Int, Int) = (a / b, a % b)
pub fn main() -> Unit !io = {
let (q, r) = divmod(17, 5)
println("$q remainder $r")
}
Open in playground
3 remainder 2