6.4.2 Enum 매칭(Enum matching)

6.4.2 Enum 매칭(Enum matching)

열거형은 생성자로 자연스럽게 매칭될 수 있어요:

var myTree = Node(Leaf("foo"), Node(Leaf("bar"), Leaf("foobar")));
var match = switch (myTree) {
    // matches any Leaf
    case Leaf(_): "0";
    // matches any Node that has r = Leaf
    case Node(_, Leaf(_)): "1";
    // matches any Node that has
    // r = another Node, which has
    // l = Leaf("bar")
    case Node(_, Node(Leaf("bar"), _)): "2";
    // matches anything
    case _: "3";
  }
trace(match); // 2

패턴 매처는 각 case를 위에서 아래로 검사하고 입력 값과 일치하는 첫 번째 것을 고릅니다. 각 case 규칙의 수동 해석이 과정 이해를 돕습니다:

  • case Leaf(_): myTreeNode이므로 매칭 실패
  • case Node(_, Leaf(_)): myTree의 오른쪽 하위 트리가 Leaf가 아니라 다른 Node이므로 매칭 실패
  • case Node(_, Node(Leaf("bar"), _)): 매칭 성공
  • case _: 이전 줄이 매칭했으므로 여기서는 검사되지 않음

출처: Enum matching

본문

enum 생성자를 패턴으로 직접 매칭해요. 중첩 구조도 Node(_, Leaf(_))처럼 표현할 수 있으며, 위에서 아래로 첫 일치 case가 선택됩니다.

더 알아보기