首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >这种模式匹配在OCaml中并不详尽。

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

Stack Overflow用户
提问于 2014-03-29 21:18:41
回答 1查看 5K关注 0票数 3

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

代码语言:javascript
复制
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解释器运行它时,一个警告生成如下:

代码语言:javascript
复制
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.

当我用:

代码语言:javascript
复制
Printf.printf "%s\n" (n_elem ["a";"b";"c";"d"] 1);;

它产生match_failure..。

有人能帮我一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-29 21:30:07

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

代码语言:javascript
复制
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
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22737031

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档