다음을 통해 공유


일치 식(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이 실행되고 그 결과 값이 일치 식의 값으로 반환됩니다.

위 구문에 나와 있는 패턴 일치 함수는 인수에 대해 패턴 일치 여부를 즉시 확인하는 람다 식입니다. 위 구문에 나와 있는 패턴 일치 함수를 다음과 같이 표현할 수도 있습니다.

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# 언어 참조