Anyway I just implemented a function for sorting a list in descending
order. It seems so fundamental and useful that I find it hard to
believe it does not already exist in Data.List. It must exist but in
some form so abstract that I do not recognize it?
This is my implementation, which seems pretty decent to me (much
better than brute force sort then reverse):
*** BEGINNING OF FILE ***
module ChipSort (
descending,
dsort
) where
import Data.List
descending :: (Ord a) => a -> a -> Ordering
descending a b
| a < b = GT --reverse meaning!
| a > b = LT --reverse meaning!
| otherwise = EQ
{-
Descending Sort
-}
-- type signature necessary due to the 'dreaded' monomorphism
restriction
dsort :: (Ord a) => [a] -> [a]
dsort = sortBy descending
***END OF FILE***
I like my implementation, but it is probably somewhat better to use
standard libraries. This has to be in the libraries somewhere,
right?! Or perhaps its such a small amount of functionality that it's
not worth adding?
(P.S. I don't really understand the monomorphism restriction, I just
read that type signature can often make the error go away)
> Anyway I just implemented a function for sorting a list in descending
> order. It seems so fundamental and useful that I find it hard to
> believe it does not already exist in Data.List. It must exist but in
> some form so abstract that I do not recognize it?
sortDesc :: Ordering a => [a] -> [a]
sortDesc = sortBy (flip compare)
> (P.S. I don't really understand the monomorphism restriction, I just
> read that type signature can often make the error go away)
The monomorphism restriction is there for technical reasons. To avoid
the error, just add a type signature for all functions you write.
That's good programming style anyway, so you don't lose much here, but
gain a lot. Usually looking at the name together with the type of a
function makes clear what the function does.
Greets,
Ertugrul.
--
nightmare = unsafePerformIO (getWrongWife >>= sex)
You could write
descending a b = compare b a
or alternatively:
descending = flip compare
or even:
reversedSortBy f = sortBy (flip f)
reversedSort = reversedSortBy compare
> (P.S. I don't really understand the monomorphism restriction, I just
> read that type signature can often make the error go away)
The monomorphism restriction is a historical weirdness and I think the
general view these days is that it was a bad idea. You can turn it off
by putting
{-# LANGUAGE NoMonomorphismRestriction #-}
at the top of your program.