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 模式手動進行模式比對:
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)"
在模式比對時,單獨的'_'一定要放在_最後_,任何_不符合_其他情況的值,都會由這個情況來處理。
你是個熱衷賞鳥的人,會持續記錄過去 7 天有多少鳥造訪你的花園。
你有 6 項任務,全都和造訪你花園的鳥的數量有關。
為了方便比較,你總會在身邊留一份上週的數量紀錄,分別是: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 開始,陣列中的第一個元素對應的是奇數日)