陣列

陣列 在 F#

3 個練習

關於 陣列

F# 中的array是固定長度、可包含零個或多個值的可變集合。這表示陣列一旦建立,大小就無法改變,但值可以改變。陣列中的值都必須具有相同型別。陣列可以如下定義:

let empty = [| |]
let emptyAlternative = Array.empty

let singleValue = [| 5 |]
let singleValueAlternative = Array.singleton 5

let threeValues = [| "a"; "b"; "c" |]

可以使用使用索引將元素指定給陣列,或從陣列中取得。F# 陣列是從 0 開始的,也就是第一個元素的索引永遠是 0:

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)"

在模式比對時,單一的'_'應該總是要放在_最後_,任何_不符合_其他情況的值,都會由這個情況處理。

透過 GitHub 編輯 連結會在新視窗或分頁中開啟

學習 陣列

練習已鎖定

再解鎖 2 個練習,就能練習 陣列