[Haskell-cafe] The maximum/minimum asymmetry

Alexander Dunlap alexander.dunlap at gmail.com
Mon Sep 5 08:35:30 CEST 2011


On 4 September 2011 21:44, Mario Blažević <blamario at acanac.net> wrote:
>    I was recently surprised to discover that the maximum and maximumBy
> functions always return the *last* maximum, while minimum and minimumBy
> return the *first* minimum in the list. The following GHCi session
> demonstrates this:
>
> $ ghci
> GHCi, version 7.2.1: http://www.haskell.org/ghc/  :? for help
> Loading package ghc-prim ... linking ... done.
> Loading package integer-gmp ... linking ... done.
> Loading package base ... linking ... done.
> Loading package ffi-1.0 ... linking ... done.
> Prelude> :module +Data.List Data.Ord
> Prelude Data.List Data.Ord> let list = [(1, 'B'), (1, 'A')]
> Prelude Data.List Data.Ord> maximumBy (comparing fst) list
> (1,'A')
> Prelude Data.List Data.Ord> minimumBy (comparing fst) list
> (1,'B')
>
>    I would normally consider this kind of gratuitous asymmetry a bug, but
> seeing that these functions' implementations have been specified in the
> Haskell 98 Library Report, I guess they are now a permanent feature of the
> language. Can anybody explain the reason for this behaviour?
>
>
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>

The asymmetry is a result of EQ and LT being treated as equivalent in
both the minBy and maxBy helper functions in the report's definition
of the two functions, which has opposite effects for minimumBy and
maximumBy. Since the documentation doesn't specify a behavior for
equal values, I could guess that it was just an oversight or that it
was considered unimportant. But maybe someone more knowledgeable will
correct me.

Alexander Dunlap



More information about the Haskell-Cafe mailing list