Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - What does the type Ord a mean?

Tags:

types

haskell

I'm creating a merge sort function in Haskell that is recursive. I have been told as part of my assessment that I must define the type as:

isort :: Ord a => [a] -> [a]

I assumed the function expects an array as input and outputs an array. I know that ord is a class.

In the context above what does the Ord a mean?

This is my function:

isort :: Ord a => [a] -> [a]
isort [x] = [x]
isort (x:xs) = insert x (isort xs)
    where
        insert :: Int -> [Int] -> [Int]
        insert a [] = []
        insert a (b:c) | a < b      = a:b:c
                       | otherwise  = b : insert a c

When I try to load my functions file into ghci I get the error:

Couldn't match type ‘a’ with ‘Int’
  ‘a’ is a rigid type variable bound by
      the type signature for isort :: Ord a => [a] -> [a]
      at LabSheet2.hs:17:10
Expected type: [a]
Actual type: [Int]
...
like image 369
nonsequiter Avatar asked Dec 14 '22 10:12

nonsequiter


1 Answers

The Ord a is a typeclass constraint that indicates your function works for any type a, so long as a is comparable (Orderable). The error message you're getting is due to the conflict between your outer declaration that says it works for any Ord a => a, and the inner insert that "only" works for Int's.

like image 177
ryachza Avatar answered Dec 21 '22 09:12

ryachza