这种模式匹配在OCaml中并非详尽无遗

时间:2014-03-29 21:18:41

标签: ocaml

我是OCaml的新手,我写了一些代码来获取列表的n元素

let rec n_elem l n = match n with
| 0 -> match l with
    | h::_ -> h
    | _ -> failwith "erorr with empty list"
| _ -> match l with
    | h::t -> n_elem t (n-1)
    | _ -> failwith "erorr with empty list"
;;

当我使用ocaml解释器运行它时,警告生成为:

Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
1
Warning 11: this match case is unused.

当我用它运行时:

Printf.printf "%s\n" (n_elem ["a";"b";"c";"d"] 1);;

它会生成match_failure ...

有人能给我一些帮助吗?

1 个答案:

答案 0 :(得分:4)

这基本上是一个优先问题。第二个_匹配案例是第二个match表达式的一部分。您可以使用开始/结束将它们分开:

let rec n_elem l n = match n with
| 0 -> 
    begin
    match l with
    | h::_ -> h
    | _ -> failwith "erorr with empty list"
    end
| _ ->
    begin
     match l with
    | h::t -> n_elem t (n-1)
    | _ -> failwith "erorr with empty list"
    end