Array Pattern
An array pattern is a sequence of patterns enclosed in []
that matches an array.
You can use ..
to match the rest of the array at the start, end, or middle elements of the array.
In an array pattern, the ..
part can be bound to a new variable via an alias pattern. The type of that variable is ArrayView
. The sum
function uses this feature to calculate the sum of the array recursively.
fn main {
let array = [1, 2, 3, 4, 5, 6]
let [a, b, ..] = array
let [.., c, d] = array
let [e, .., f] = array
println("a: \{a}, b: \{b}")
println("c: \{c}, d: \{d}")
println("e: \{e}, f: \{f}")
println("sum of array: \{sum(array[:])}")
}
fn sum(array : ArrayView[Int]) -> Int {
match array {
[] => 0
[x, .. as xs] => x + sum(xs)
}
}