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(_):myTree가Node이므로 매칭 실패case Node(_, Leaf(_)):myTree의 오른쪽 하위 트리가Leaf가 아니라 다른Node이므로 매칭 실패case Node(_, Node(Leaf("bar"), _)): 매칭 성공case _: 이전 줄이 매칭했으므로 여기서는 검사되지 않음
출처: Enum matching
본문
enum 생성자를 패턴으로 직접 매칭해요. 중첩 구조도 Node(_, Leaf(_))처럼 표현할 수 있으며, 위에서 아래로 첫 일치 case가 선택됩니다.