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

问题描述 投票:0回答:2

我是 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...

有人可以帮我吗?

ocaml
2个回答
6
投票

这基本上是一个优先级问题。第二个

_
匹配案例是第二个
match
表达式的一部分。您可以使用开始/结束将它们分开:

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

0
投票

除了 Jeffrey 非常正确地指出的之外,这里没有必要嵌套

match
表达式。相反,我们可以匹配
n
l
的元组。

这也让我们避免重复代码(相同的异常被引发两次)。

let rec n_elem l n = 
  match n, l with
  | 0, h::_ -> h
  | _, _::t -> n_elem t (n-1)
  | _, [] -> failwith "error with empty list"
© www.soinside.com 2019 - 2024. All rights reserved.