这种模式匹配在OCaml中并不详尽 [英] this pattern-matching is not exhaustive in OCaml

查看:28
本文介绍了这种模式匹配在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_elem ["a";"b";"c";"d"] 1);;

它会生成MATCH_FAILURE.

有人能帮我一下吗?

推荐答案

这基本上是优先问题。第二个_大小写匹配是第二个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

这篇关于这种模式匹配在OCaml中并不详尽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆