this pattern-matching is not exhaustive in OCaml

拟墨画扇 提交于 2019-12-11 02:41:43

问题


I am new in OCaml and I wrote some code to get the n element of a list

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"
;;

When I run it using ocaml interpreter, an warning generate as:

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.

and when I run it with:

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

it generate match_failure...

Could anyone give me some help?


回答1:


This is basically a precedence problem. The second _ match case is part of the second match expression. You can use begin/end to keep them separate:

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


来源:https://stackoverflow.com/questions/22737031/this-pattern-matching-is-not-exhaustive-in-ocaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!