[Haskell-cafe] is there already a function that does this?

Matthew Brecknell haskell at brecknell.org
Sat Mar 3 17:31:17 EST 2007


Jared Jennings:
> -- Sort the [a]'s by the [b]'s.
> sortByKeys :: (Ord b) => [b] -> [a] -> [a]
> sortByKeys keys values = map snd $ sortBy compareFst (zip keys values)
>    where compareFst x y = compare (fst x) (fst y)

Henk-Jan van Tuyl:
> You can simplify that to:
> 
>    sortByKeys :: (Ord b) => [b] -> [a] -> [a]
>    sortByKeys keys values = map snd $ sort $ zip keys values
> 
> as "sort" also handles tuples; it is not fully identical, in case there  
> are duplicate keys:
> 
>    Data.List> sort [(2, 2), (2, 1), (1, 2), (1, 1)]
>    [(1,1),(1,2),(2,1),(2,2)]

The modified version would require an ordering for the values as well as
the keys, so it actually has a different type:

sortByKeys :: Ord (b,a) => [b] -> [a] -> [a]

The original didn't place any restrictions on the values.



More information about the Haskell-Cafe mailing list