match 式 (F#)

match 式は、式を一連のパターンと比較し、その比較に基づいて分岐を制御します。

// Match expression.
match test-expression with
    | pattern1 [ when condition ] -> result-expression1
    | pattern2 [ when condition ] -> result-expression2
    | ...

// Pattern matching function.
function
    | pattern1 [ when condition ] -> result-expression1
    | pattern2 [ when condition ] -> result-expression2
    | ...

解説

パターン マッチ式は、テスト式を一連のパターンと比較し、その比較に基づいて複雑な分岐を制御できるようにします。match 式では、test-expression が各パターンと順に比較され、一致が見つかると、対応する result-expression が評価されて、結果値が match 式の値として返されます。

前の構文で示したパターン マッチ関数は、パターン マッチが引数で直ちに実行されるラムダ式です。前の構文で示したパターン マッチ関数は、次の構文と同じ結果になります。

fun arg ->

match arg with

|pattern1 [ when condition ] -> result-expression1

|pattern2 [ when condition ]-> result-expression2

| ...

ラムダ式の詳細については、「ラムダ式: fun キーワード (F#)」を参照してください。

一連のパターン全体が、入力変数のすべての一致を対象にしている必要があります。多くの場合、これまでに一致しなかった入力値に対応するための最後のパターンとして、ワイルドカード パターン (_) が使用されます。

次のコードは、match 式を使用する方法を示しています。使用できるすべてのパターンのリファレンスと例については、「パターン マッチ (F#)」を参照してください。

let list1 = [ 1; 5; 100; 450; 788 ]

// Pattern matching by using the cons pattern and a list
// pattern that tests for an empty list.
let rec printList listx =
    match listx with
    | head :: tail -> printf "%d " head; printList tail
    | [] -> printfn ""

printList list1

// Pattern matching with multiple alternatives on the same line.  
let filter123 x =
    match x with
    | 1 | 2 | 3 -> printfn "Found 1, 2, or 3!"
    | a -> printfn "%d" a

// The same function written with the pattern matching
// function syntax.
let filterNumbers =
    function | 1 | 2 | 3 -> printfn "Found 1, 2, or 3!"
             | a -> printfn "%d" a

パターンのガード

when 句を使用して、変数が必ずパターンに一致するという追加の条件を指定できます。このような句をガードと呼びます。ガードに関連付けられているパターンに一致しない限り、when キーワードの後に続く式は評価されません。

ガードを使用して変数パターンの数値の範囲を指定する方法を次の例に示します。条件が複数ある場合は、ブール演算子で結合しています。

let rangeTest testValue mid size =
    match testValue with
    | var1 when var1 >= mid - size/2 && var1 <= mid + size/2 -> printfn "The test value is in range."
    | _ -> printfn "The test value is out of range."

rangeTest 10 20 5
rangeTest 10 20 10
rangeTest 10 20 40

リテラル以外の値はパターンで使用できないため、入力の一部を値と比較する必要がある場合は、when 句を使用してください。コードは次のようになります。

// This example uses patterns that have when guards.
let detectValue point target =
    match point with
    | (a, b) when a = target && b = target -> printfn "Both values match target %d." target
    | (a, b) when a = target -> printfn "First value matched target in (%d, %d)" target b
    | (a, b) when b = target -> printfn "Second value matched target in (%d, %d)" a target
    | _ -> printfn "Neither value matches target."
detectValue (0, 0) 0
detectValue (1, 0) 0
detectValue (0, 10) 0
detectValue (10, 15) 0

参照

関連項目

アクティブ パターン (F#)

その他の技術情報

F# 言語リファレンス