Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell: SortBy with multiple parameters (Birth dates)

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.

like image 799
Dystr Avatar asked Dec 11 '22 08:12

Dystr


1 Answers

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 EQs and non-EQs, 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)
like image 65
Daniel Wagner Avatar answered Dec 27 '22 12:12

Daniel Wagner