这种模式匹配在 OCaml 中并不详尽

lll*_*lll 3 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"
;;
Run Code Online (Sandbox Code Playgroud)

当我使用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.
Run Code Online (Sandbox Code Playgroud)

当我运行它时:

Printf.printf "%s\n" (n_elem ["a";"b";"c";"d"] 1);;
Run Code Online (Sandbox Code Playgroud)

它生成 match_failure...

谁能给我一些帮助?

Jef*_*eld 5

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

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
Run Code Online (Sandbox Code Playgroud)