0
votes

I have been going through the Seven Languages in Seven Weeks book and I'm working with Haskell.

I am struggling with the problem:

Write a sort that takes a list and a function that compares its two arguments and then returns a sorted list.

I searched online for help and found a solution but I can't even get the solution to run because of an expected to actual type error.

Here is the code I've been trying:

module Main where
import Data.List
sortList :: (Ord a) => (a -> a -> Ordering) -> [a] -> [a]
sortList comparator list = sortBy comparator list

Here is the error:

*Main> sortList [5,4,2,7,8,1]

<interactive>:1:10:
    Couldn't match expected type `a -> a -> Ordering'
                with actual type `[t]'
    In the first argument of `sortList', namely `[5, 4, 2, 7, ....]'
    In the expression: sortList [5, 4, 2, 7, ....]
    In an equation for `it': it = sortList [5, 4, 2, ....]

My Thoughts and Attempts:

Maybe I am calling the function wrong? I am fairly new to Haskell. II tried doing many searches as well. All I could conclude is that somewhere the types aren't matching up. I suppose explanation and guidance for the script would be very helpful to me.

2
Well your signature already says it: calling sortList requires a comparator you did not provide...Willem Van Onsem

2 Answers

2
votes

Your function signature says:

"sortList is a function that takes:"

  • function (a -> a -> Ordering) that take two elements of type 'a' and returns an 'Ordering' [this is your comparator]
  • List of items 'a' ([a]) that you are passing it
  • Returns a list of items 'a' ([a])

Try call them in this way:

sortList compare [3,2,1]

For more read here: https://hackage.haskell.org/package/base-4.8.2.0/docs/Data-Ord.html

and here: http://zvon.org/other/haskell/Outputprelude/compare_f.html

1
votes

You are calling the function wrong, you need to pass it a comparator function. You just pass a list to the function.