Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inconsistency between minimumBy and maximumBy

Tags:

haskell

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))

like image 303
yairchu Avatar asked Dec 03 '22 12:12

yairchu


1 Answers

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.

like image 142
David Fletcher Avatar answered Jan 02 '23 09:01

David Fletcher