So i am given this
intCMP :: Int -> Int -> Ordering
intCMP a b | a == b = EQ
| a < b = LT
| otherwise = GT
intCMPRev :: Int -> Int -> Ordering
intCMPRev a b | a == b = EQ
| a < b = GT
| otherwise = LT
floatCMP :: Float -> Float -> Ordering
floatCMP a b | a == b = EQ
| a < b = LT
| otherwise = GT
I need to write this function
sort3 :: Ord a => (a -> a-> Ordering) -> [a] -> [a]
sort3 cmp xs =
Which will sort 3 or less elements by comparison. No recursion. I was wondering how this works as far as passing say intCMP. Why would you pass that into the sort function? Does it serve a purpose when sorting and returning the sorted list? I’m not really sure how to do the comparisons manually like that without any sort of recursive call, so I’m just trying to understand it better.
I was thinking of doing 3 comparisons and then moving the element to a certain position in the list, but i really don’t know how i could even do this in haskell. Any clues on how to start this would be great. Maybe some sort of pattern?
Thanks.
Partial answer to the first part of your question:
Passing in
intCMPtosort3lets you control the way the sorting is done. Presumably,sort3 intCMP [7,3,6]will return[3,6,7], whereassort3 intCMPRev [7,3,6]will return[7,6,3]. You could even make your own weird sorting functions like first all the even numbers and then all the odd ones in descending order, like so:Using this,
sort3 intCMPWeird [7,3,6]should give[6,7,3].What happens during typechecking when you pass one of the
intCMP...functions intosort3is (in a very small nutshell) that the compiler tries to match the type ofsort3‘s first argument(a -> a -> Ordering)with the type of the supplied value(Int -> Int -> Ordering)and succeeds in doing that, by makingaequal toInt. Then it needs to check whether the constraintOrd ais satisfied forInt, which works! Finally the compiler can figure out that the type ofsort3 intCMPis[Int] -> [Int]. Similarly,sort3 floatCMPhas type[Float] -> [Float].I’m not 100% sure why the
Ordconstraint is on the type ofsort3, since you can get the needed information from the passed-in comparison function – are you sure you’ve typed that correctly?EDIT: Hint on how to use a where clause to get a readable definition, you still have to fill in some bits and add some more clauses: