Hume
Hume

Reputation: 93

What is the difference between "Ord a => [a] -> [a] -> [a]" and "[a] -> [a] -> [a]"

I am new in Haskell. Can anyone explain the difference and the usage of Ord a?

Now I'm familiar with [a] -> [a] -> [a] things. But this,

Ord a => [a] -> [a] -> [a]

please explain me in detail.

Upvotes: 2

Views: 319

Answers (2)

Consider:

-- merge :: [a] -> [a] -> [a]  ?
merge [] ys = ys
merge xs [] = xs
merge (x:xs) (y:ys)
  | y < x     = y : merge (x:xs) ys
  | otherwise = x : merge xs (y:ys)

In particular, look at the second-to-last line. See that (<) operator?

ghci> :i (<)
class Eq a => Ord a where
  ...
  (<) :: a -> a -> Bool

We can see here that the less-than operator does not exist for type not of class Ord; that merge function therefore makes no sense unless we have Ord a. We therefore rewrite its type signature as:

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

Upvotes: 2

developer_hatch
developer_hatch

Reputation: 16214

The difference is in the constraint, Ord a => a here a has type a but not any a, an a that is an instance of Ord typeclass, example:

here I will change a little bit the type result only to show you can use the functions of the interface:

canBeOrderedList :: Ord a => [a] -> [a] -> [Bool]
canBeOrderedList xs ys = zipWith (>) xs ys

here you can do whatever generic function you want, a here is not restricted, so it can be Ord or Eq or both or none, can be functions, can be Ints can be anything

anyListTypeConcat :: [a] -> [a] -> [a]
anyListTypeConcat xs ys  = xs ++ ys 

so:

anyListTypeConcat [True, False] [False, True]
=> [True,False,False,True]

here you concatted the two list, so far so good, here:

canBeOrderedList [1,2,3] [4,1,2]
=> [False,True,True]

you can use (>) with numbers but, what about:

data Some = A | B | C deriving (Eq, Show)

anyListTypeConcat [A, A] [B, C]
=> [A,A,B,C]

but:

canBeOrderedList [A,A,B] [C,A,A]
 error:
    • No instance for (Ord Some)
        arising from a use of ‘canBeOrderedList’
    • In the expression: canBeOrderedList [A, A, B] [C, A, A]
      In an equation for ‘it’: it = canBeOrderedList [A, A, B] [C, A, A]

You cannot order that list, but you may if you change the data type:

data Some = A | B | C deriving (Eq, Show, Ord)
canBeOrderedList [A,A,B] [C,A,A]
=> [False,False,True]

And that's essentially the difference

Upvotes: 3

Related Questions