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模块中定义的函数和运算符,或者使用 数组 模式手动进行模式匹配:
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)"
模式匹配时,单个'_'应该始终放在_最后_,所有与其它分支都不匹配的值都会由这个分支来处理。
你是一位热心的观鸟爱好者,一直在记录过去七天里有多少只鸟来过你的花园。
你有六个任务,全都和来你花园的鸟的数量有关。
为了便于比较,你总是把上周的计数留一份在手边,它们是:0、2、5、3、7、8 和 4。定义lastWeek绑定,用来存放上周的计数:
lastWeek
// => [| 0; 2; 5; 3; 7; 8; 4 |]
实现yesterday函数,返回昨天来你花园的鸟的数量。鸟类计数按天排列:第一个元素是最早那天的计数,最后一个元素是今天的计数。
yesterday [| 3; 5; 0; 7; 4; 1 |]
// => 4
实现total函数,返回来你花园的鸟的总数:
total [| 3; 5; 0; 7; 4; 1 |]
// => 20
实现dayWithoutBirds函数,如果有一天没有鸟来花园,就返回true;否则返回false:
dayWithoutBirds [| 3; 5; 0; 7; 4; 1 |]
// => true
实现incrementTodaysCount函数,把今天的计数自增,并返回更新后的计数:
let birdCount = [| 3; 5; 0; 7; 4; 1 |]
incrementTodaysCount birdCount
// => [| 3; 5; 0; 7; 4; 2 |]
在过去一年里,你发现有些星期会出现同样的、不寻常的模式:
实现unusualWeek函数,如果这一周的鸟类计数模式符合其中一种不寻常模式,就返回true:
unusualWeek [| 1; 0; 5; 0; 12; 0; 2 |]
// => true
unusualWeek [| 5; 0; 5; 12; 5; 3; 5|]
// => true
(注意,天的奇偶性从 1 开始计数,而不是从 0 开始,数组的第一个元素对应奇数天)