Search code examples
haskellquicksortempty-list

Empty list in Haskell is not running in function even though I have a base case checking for empty lists


    -- quick sort a list in Haskell
qsort :: Ord a => [a] -> [a]  
-- check to see if the list is empty
qsort [] = []
-- if the list is  not empty split the list by the head/first element and the rest of the list...
qsort (x:xs) = 
  -- create one list for the smaller elements in the list that will use quick sort recursively
  let small = qsort [a | a <- xs, a <= x]
      --create one list for the larger elements in the list that will use quick sort recursively
      big = qsort [a | a <- xs, a > x]
  -- return the combined lists of the smaller elements list with the original head of the list with the bigger elements list
  in small ++ [x] ++ big

list1 = [5, 6, 2, 3, 7, 4, 6, 2, 7, 4]
list2 = [5, 6, 2, 3, 6, 0, 3, 9, 8, 0]
liste = []
list3 = [-4, 5, -8, 0, -3, 2 ,4]

main:: IO ()

main = 
  do
    print(qsort list1)
    print(qsort list2)
    print(qsort list3)
    print(qsort liste)

The error I keep getting is:

Main.hs:29:11: error:
• Ambiguous type variable ‘a0’ arising from a use of ‘qsort’
  prevents the constraint ‘(Ord a0)’ from being solved.
  Probable fix: use a type annotation to specify what ‘a0’ should be.
  These potential instances exist:
    instance Ord Ordering -- Defined in ‘GHC.Classes’
    instance Ord Integer
      -- Defined in ‘integer-gmp-1.0.3.0:GHC.Integer.Type’
    instance Ord a => Ord (Maybe a) -- Defined in ‘GHC.Maybe’
    ...plus 22 others
    ...plus four instances involving out-of-scope types
    (use -fprint-potential-instances to see them all)
• In the first argument of ‘print’, namely ‘(qsort liste)’
  In a stmt of a 'do' block: print (qsort liste)
  In the expression:
    do print (qsort list1)
       print (qsort list2)
       print (qsort list3)
       print (qsort liste)    | 29 |     print(qsort liste)    |           ^^^^^^^^^^^ Failed, no modules loaded.   <interactive>:1:1: error:
• Variable not in scope: main
• Perhaps you meant ‘min’ (imported from Prelude)

Solution

  • The type needs to be disambiguated with an explicit signature:

    liste :: [Integer]
    liste = []
    list1 = [5, 6, 2, 3, 7, 4, 6, 2, 7, 4]
    list2 = [5, 6, 2, 3, 6, 0, 3, 9, 8, 0]
    list3 = [-4, 5, -8, 0, -3, 2 ,4]