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

Jared Jennings jjenning at gmail.com
Sat Mar 3 16:35:00 EST 2007

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

-- Sort a list by an IO-returning compare function.
sortByM :: (Monad m, Ord b) => (a -> m b) -> [a] -> m [a]
sortByM fun lis = mapM fun lis >>= \keys -> return $ sortByKeys keys lis

Is there a function that can make sortByM out of sortByKeys? I don't
know of one, but having been writing haskell for a few weeks, it sort
of smells to me like there probably is one.

More information about the Haskell-Cafe mailing list