我是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..。
有人能帮我一下吗?
发布于 2014-03-29 21:30:07
这基本上是一个优先问题。第二个_匹配情况是第二个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"
endhttps://stackoverflow.com/questions/22737031
复制相似问题