我想比较两个整数列表。我从模式匹配开始,但在嵌套匹配方面遇到问题,所以尝试了另一种方法。
我收到警告,模式匹配并不详尽,它表示列表可以为空。这很奇怪,因为我一开始就检查过。
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;;
关于pattern-matching - 在 OCaml 中比较两个整数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37530682/