比较 OCaml 中的两个整数列表

Compare two integer lists in 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>

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

而且你的if比较多,还是用match比较好,可读性更好。例如:

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