首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较OCaml中的两个整数列表

比较OCaml中的两个整数列表
EN

Stack Overflow用户
提问于 2016-05-30 17:04:15
回答 1查看 7.8K关注 0票数 2

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

我收到警告说模式匹配并不是详尽无遗的,它说列表可以是空的。这很奇怪,因为我一开始就检查过了。

代码语言:javascript
复制
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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-30 17:13:12

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

而且你有很多如果,它更好地使用匹配,它是更可读的。例如:

代码语言:javascript
复制
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;;
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37530682

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档