Skip to content

Add sortOn function to Data.List

The following passed for two weeks on the libraries mailing list without any dissenting votes.

The request is to add the following function to Data.List:

-- | Sort a list by comparing the results of a key function applied to each
--   element.  @sortOn f@ is equivalent to @sortBy . comparing f@, but has the
--   performance advantage of only evaluating @f@ once for each element in the
--   input list.  This is called the decorate-sort-undecorate paradigm, or
--   Schwartzian transform.
sortOn :: Ord b => (a -> b) -> [a] -> [a]
sortOn f = map snd . sortBy (comparing fst)
                   . map (\x -> let y = f x in y `seq` (y, x))
Trac metadata
Trac field Value
Version 7.8.2
Type FeatureRequest
TypeOfFailure OtherFailure
Priority normal
Resolution Unresolved
Component libraries/base
Test case
Differential revisions
BlockedBy
Related
Blocking
CC hvr
Operating system
Architecture
To upload designs, you'll need to enable LFS and have an admin enable hashed storage. More information