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

Henk-Jan van Tuyl hjgtuyl at chello.nl
Sat Mar 3 17:08:13 EST 2007


On Sat, 03 Mar 2007 22:35:00 +0100, Jared Jennings <jjenning at gmail.com>  
wrote:

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

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


-- 
Met vriendelijke groet,
Henk-Jan van Tuyl


--
http://Van.Tuyl.eu/
--

Using Opera's revolutionary e-mail client:
https://secure.bmtmicro.com/opera/buy-opera.html?AID=789433



More information about the Haskell-Cafe mailing list