比较OCaml中的两个整数列表

时间:2016-05-30 17:04:16

标签: pattern-matching ocaml

我想比较两个整数列表。我从模式匹配开始,但我遇到了嵌套匹配的问题,所以尝试了另一种方式。

我收到警告说模式匹配并不详尽,它说列表可能是空的。这很奇怪,因为我在开始时检查它。

let rec cmp3 l1 l2 = 
    if l1 = [] && l2 = [] then 0 
    else if l1 = [] then -1
    else if l2 = [] then 1 else 
    let (h::t) = l1 and (hh::tt) = l2 in
    if h > hh then 1 
    else if hh > h then -1 
    else cmp3 t tt;;
              Characters 125-131:
      let (h::t) = l1 and (hh::tt) = l2 in
          ^^^^^^
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]
Characters 141-149:
      let (h::t) = l1 and (hh::tt) = l2 in
                          ^^^^^^^^
Warning 8: this pattern-matching is not exhaustive.
Here is an example of a value that is not matched:
[]
val cmp3 : 'a list -> 'a list -> int = <fun>

1 个答案:

答案 0 :(得分:2)

编译器不能假设两个列表具有相同的长度 - 这就是它发出警告的原因。如果您确信列表的长度始终相同,那么您可以放弃此警告 - 但这不是一种安全的编写程序的方法。

你也有很多ifs,最好使用匹配,它更具可读性。举个例子:

let rec cmp l ll = 
match (l,ll) with
| [], [] -> 0
| [],_ -> -1
| _,[] -> 1
| (h::t), (hh::tt) -> if h > hh then 1
                      else if h < hh then -1 
                      else cmp t tt;;