配列

配列 の F#

3個の演習

配列について

F#のarrayは、長さが固定された、0個以上の値からなる変更可能なコレクションです。つまり、一度配列を作成すると、そのサイズは変更できませんが、値は変更できます。配列内の値は、すべて同じ型でなければなりません。配列は次のように定義できます:

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個の演習のロックを解除してください