Lecture 14-1
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
showTuple :: (Show a, Show b) => (a, b) -> [Char]
addThree :: (Num a, Read a) => String -> a
headLt10 :: (Num a, Ord a) => [a] -> Bool