F# 中的array是一种长度固定的可变集合,可以存放零个或多个值。这意味着数组一旦创建,其大小就无法改变,但其中的值可以改变。数组中的所有值都必须具有相同的类型。数组可以这样定义:
let empty = [| |]
let emptyAlternative = Array.empty
let singleValue = [| 5 |]
let singleValueAlternative = Array.singleton 5
let threeValues = [| "a"; "b"; "c" |]
借助下标,既可以给数组中的元素赋值,也可以从数组中读取元素。F# 数组的下标从零开始,也就是说第一个元素的下标始终为零:
let numbers = [| 2; 3; 5 |]
// Update value in array
numbers[2] <- 9
// Read value from array
numbers[2]
// => 9
对数组的操作由Array模块中定义的函数和运算符完成。其中一些函数也可以作为array实例的属性使用:
Array.length [| 7; 8 |] // => 2
[| 7; 8 |].Length // => 2
这两种方式没有对错之分。一般来说,Array模块中的函数与类型推断配合得更好,而属性则可以让代码更简洁。
数组模式允许对数组进行模式匹配:
let describe array =
match array with
| [| |] -> "Empty"
| [| 1; 2; three |] -> sprintf "1, 2, %d" three
| _ -> "Other"
describe [| |] // => "Empty"
describe [| 1; 2; 4 |] // => "1, 2, 4"
describe [| 5; 7; 9 |] // => "Other"
进行模式匹配时,你也可以_丢弃_某个值;如果你在某个分支中_不_关心某个值(也就是说你不会_用到_这个值),可以用下划线('_')来表示:
let describe array =
match array with
| [| |] -> "Empty array"
| [| x |] -> "Array with one item"
| [| _; y |] -> "Array with two items (first item ignored)"
| _ -> "Array with many items (all items ignored)"
describe [| |] // => "Empty array"
describe [| 1 |] // => "Array with one item"
describe [| 5; 7 |] // => "Array with two items (first item ignored)"
describe [| 5; 7; 9 |] // => "Array with many items (all items ignored)"
进行模式匹配时,单个'_'应始终放在_最后_,任何_不_匹配其他分支的值,都会由这个分支来处理。