Ben
Ben

Reputation: 2715

Sort a list in haskell according to a predicate

I am trying to learn Haskell and I've come into issues trying to complete an example problem. The problem is to sort a list in Haskell according to a given predicate i.e. the type is

sort :: (a -> a -> Bool) -> [a] -> [a]

The code I have so far is :

sort _ [] = []
sort f (x:xs) =
            let 
            smaller = sort f (filter (f x) xs)
            bigger = sort f (filter (f x) xs) --error is on this line 
            in smaller ++ [x] ++ bigger

The code not working correctly in the sense im not sure how to take the opposite of the function. for example if it were an ordinary sort function I would use smaller = quicksort (filter (<=x) xs) and bigger = quicksort (filter (>x) xs) this would then break up the list according to that predicate but how do I do this with a higher order predicate?

Upvotes: 0

Views: 1763

Answers (1)

bheklilr
bheklilr

Reputation: 54058

You just need to use the not function to invert your boolean:

not :: Bool -> Bool

f :: a -> a -> Bool
f x :: a -> Bool

not . f x :: a -> Bool

And you'd use it as

sort _ [] = []
sort f (x:xs) =
    let smaller = sort f (filter (f x) xs)
        bigger  = sort f (filter (not . f x) xs)
    in smaller ++ [x] ++ bigger

Upvotes: 3

Related Questions