Reputation: 421
I want to compare two integer lists. I started with pattern matching but I had a problem with nesting matches so tried another way.
I'm getting warnings that pattern-matching is not exhaustive, it says that list can be empty. That's strange since I check that at the beginning.
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>
Upvotes: 2
Views: 9540
Reputation: 4431
The compiler cannot assume that both list have the same length - this is why it issues a warning. If you are confident that your list have always the same length, then up to you to discard this warning - but that is not a safe way to write programs.
Also you have many ifs, it is better to use match, it is more readable. As an example :
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;;
Upvotes: 3