When Data.List.minimumBy
comes across list elements that are equal, it chooses the one that came first, but maximumBy
chooses the last one:
> import Data.List
> import Data.Ord
> minimumBy (const (const EQ)) "Hello world!"
'H'
> maximumBy (const (const EQ)) "Hello world!"
'!'
Is this by design or by coincidence? Is there a good reasoning behind this behavior?
Note that taking advantage of such an assumption can make code much more succinct - i.e minimumOn length texts
instead of using an explicit tie-breaker such as map snd (minimumOn (\(p, t) -> (length t, p)) (zip [0..] texts))
In the Haskell report there is a comment about min and max:
-- note that (min x y, max x y) = (x,y) or (y,x)
max x y
| x <= y = y
| otherwise = x
min x y
| x <= y = x
| otherwise = y
minimumBy
and maximumBy
are probably using these or at least trying to stay consistent with them.
I would guess the reason is that you might use min and max to, say, write a sort that involved comparing and swapping pairs (as in the operation in the comment above). Without this property you could lose elements and have others duplicated.
You normally wouldn't be able to observe any difference, since things that compare equal are usually completely identical. But you can imagine having elements with some sort of internal structure that isn't considered by comparisons but that you would not want to be lost during a sort.
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