我想比较两个整数列表。我从模式匹配开始,但是嵌套匹配有问题,所以尝试了另一种方法。
我收到警告说模式匹配并不是详尽无遗的,它说列表可以是空的。这很奇怪,因为我一开始就检查过了。
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>发布于 2016-05-30 17:13:12
编译器不能假设这两个列表都有相同的长度--这就是它发出警告的原因。如果您确信列表的长度总是相同的,那么就由您来放弃此警告--但这并不是编写程序的安全方法。
而且你有很多如果,它更好地使用匹配,它是更可读的。例如:
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;;https://stackoverflow.com/questions/37530682
复制相似问题