Skip to content
UoL CS Notes

Lecture 14-1

COMP105 Lectures

More Type Classes

show

This function converts other types to strings. However, it can only take the type class of Show into a string:

show :: Show a => a -> a

Show contains:

  • All basic types.
  • All tuples of show-able types.
  • All lists of show-able types.

read

This converts strings to other types, provided they are formatted correctly:

read "123" :: Int

In this case the use of :: is necessary to tell Haskell what type the function should return.

In cases where type inference can be used, the :: is not required:

not (read "False")

The type of read is the type class Read:

read :: Read a => a -> a

Read contains:

  • All basic types.
  • All tuples of readable types.
  • All lists of readable types.

Ordered Types

The type class to compare two objects by inequality is Ord. This is required for using functions such as >.

(>) :: Ord a -> a -> a -> Bool

All basic types can be compared including tuples and lists. Tuples and lists are compared lexicographically (similar to alphabetically ordering words).

Exercises

  1. showTuple :: (Show a, Show b) => (a, b) -> [Char]
  2. addThree :: (Num a, Read a) => String -> a
  3. headLt10 :: (Num a, Ord a) => [a] -> Bool