OCaml에서 case _에 해당하는 패턴 매칭 (pattern matching) 구문은 match ... with _ -> ... 입니다.
Scala의 case _ => ...와 동일한 역할을 하며, **어떤 값이든 매칭하는 "기본 경우"**를 의미합니다.
_ 사용let describe_list lst =
match lst with
| [] -> "빈 리스트"
| [x] -> Printf.sprintf "한 개의 요소: %d" x
| _ -> "여러 개의 요소"
;;
print_endline (describe_list []);; (* 빈 리스트 *)
print_endline (describe_list [42]);; (* 한 개의 요소: 42 *)
print_endline (describe_list [1;2;3]);; (* 여러 개의 요소 *)
[] → 빈 리스트인 경우.[x] → 요소가 하나만 있는 리스트._ → 위의 경우에 해당하지 않는 나머지 모든 리스트._ 사용let describe_tuple t =
match t with
| (0, y) -> Printf.sprintf "첫 번째 요소가 0, 두 번째 요소는 %d" y
| (_, _) -> "일반적인 튜플"
;;
print_endline (describe_tuple (0, 10));; (* 첫 번째 요소가 0, 두 번째 요소는 10 *)
print_endline (describe_tuple (5, 7));; (* 일반적인 튜플 *)
(0, y) → 첫 번째 요소가 0인 경우.(_, _) → 어떤 두 개의 요소든 해당하는 경우.let describe_option opt =
match opt with
| Some x -> Printf.sprintf "값이 있음: %d" x
| None -> "값이 없음"
;;
print_endline (describe_option (Some 10));; (* 값이 있음: 10 *)
print_endline (describe_option None);; (* 값이 없음 *)
Some x → Some 값을 가지는 경우.