I'm trying to sort a list of Birth dates according to Y > M > D priorities using sortBy.
Since nesting guards isn't possible, I've come up with this kind of ugly solution:
sortBD (day1, month1, year1) (day2, month2, year2)
| year1 < year2 = GT
| year1 < year2 = LT -- Typo: < should be >
| year1 == year2 = if compare month1 month2 == EQ then compare day1 day2 else compare month1 month2
This however returns an Exception due to non exhaustive patterns.
[EDIT]: To save others running into issues with the same problem the confusion: The problem in the code above is a typo, as pointed out in answers, not the approach itself.
You haven't covered the year1 > year2
case, because you have a typo on this line:
| year1 < year2 = GT
Instead of trying to carefully juggle EQ
s and non-EQ
s, you can just use the Monoid
instance for Ordering
to combine results:
sortBD (d1, m1, y1) (d2, m2, y2)
= compare y1 y2
<> compare m1 m2
<> compare d1 d2
Even better still, the tuple instance already does this, so you can just reuse that:
sortBD (d1, m1, y1) (d2, m2, y2) = compare (y1, m1, d1) (y2, m2, d2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With