일치 식

식은 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은 각 패턴과 차례로 비교되며 일치 항목이 발견되면 해당 결과 식이 계산되고 결과 값이 일치 식의 값으로 반환됩니다.

이전 구문에 표시된 패턴 일치 함수는 인수에서 패턴 일치가 즉시 수행되는 람다 식입니다. 이전 구문에 표시된 패턴 일치 함수는 다음과 같습니다.

fun arg ->
    match arg with
    | pattern1 [ when condition ] -> result-expression1
    | pattern2 [ when condition ] -> result-expression2
    | ...

람다 식에 대한 자세한 내용은 람다 식: 키 fun 워드를 참조하세요.

전체 패턴 집합은 입력 변수의 가능한 모든 일치 항목을 포함해야 합니다. 와일드카드 패턴(_)을 이전의 일치하지 않는 입력 값과 일치하는 마지막 패턴으로 사용하는 경우가 많습니다.

다음 코드에서는 식이 사용되는 몇 가지 방법을 match 보여 줍니다. 사용할 수 있는 모든 가능한 패턴의 참조 및 예제는 패턴 일치를 참조 하세요.

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 패턴에 맞게 충족해야 하는 추가 조건을 지정할 수 있습니다. 이러한 절을 가드라고 합니다. 키워드(keyword) 다음 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

공용 구조체 패턴이 가드에 의해 보호되면 가드는 마지막 패턴뿐만 아니라 모든 패턴에 적용됩니다. 예를 들어 다음 코드를 지정하면 가드 when a > 41 가 두 코드 모두 A a 에 적용됩니다 B a.

type Union =
    | A of int
    | B of int

let foo() =
    let test = A 42
    match test with
    | A a
    | B a when a > 41 -> a // the guard applies to both patterns
    | _ -> 1

foo() // returns 42

참고 항목