Haskell Typeclass Constraints
A typeclass constraint is a requirement that a type must belong to a class. It appears before the arrow in a type signature and limits which types a function can accept.
Eq lets a function compare values
areEqual needs only Eq. It returns True for matching values and False otherwise.
areEqual :: Eq a => a -> a -> Bool
areEqual x y = x == y
main :: IO ()
main = print (areEqual 3 3, areEqual 3 4)Stacked constraints combine Eq and Show
describe needs both classes. It shows a value when the two match and says different otherwise.
describe :: (Eq a, Show a) => a -> a -> String
describe x y = if x == y then show x else "different"
main :: IO ()
main = do
print (describe 5 5)
print (describe 5 6)Ord and Show together pick the larger value
larger needs ordering and printing. It shows the larger of its two arguments.
larger :: (Ord a, Show a) => a -> a -> String
larger x y = if x > y then show x else show y
main :: IO ()
main = do
print (larger 9 4)
print (larger 2 8)Example
describePair :: (Eq a, Show a) => a -> a -> String
describePair x y = if x == y then show x else "different"
bigger :: (Ord a, Show a) => a -> a -> String
bigger x y = if x > y then show x else show y
main :: IO ()
main = do
print (describePair 7 7)
print (describePair 7 8)
print (bigger 3 9)Key points
- Constraint: a requirement written before the arrow, such as Eq a.
- Stacked constraints: two or more requirements are separated by commas inside one pair of parentheses.
- Eq constraint: a function with Eq a can compare its arguments for equality.
- Show constraint: a function with Show a can turn its argument into text.
- Ord constraint: a function with Ord a can order its arguments.
In this example, describePair uses Eq and Show to name a match or report a mismatch. Then bigger uses Ord and Show to show the larger number. Each function states exactly the classes it needs.
Note
a constraint does not add behaviour by itself, it only asks GHC to check that the behaviour exists.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
Which signature correctly requires both Eq and Show for type a?