5. 列表、元组与模式解构
内建 List 有字面量、++ 连接、len、range、for-in。列表模式能解构头尾:
fn describe(xs: List[Int]) -> String =
match xs {
[] -> "空"
[x] -> "单个 $x"
[first, ..rest] -> "首个 $first,还有 ${len(rest)} 个"
}
pub fn main() -> Unit !io = {
println(describe([]))
println(describe([9]))
println(describe([1, 2, 3]))
}
在 Playground 打开
空
单个 9
首个 1,还有 2 个
元组打包定长异构值,let 可直接解构:
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 余 $r")
}
在 Playground 打开
3 余 2