CSCE 314 Lecture 5
Jump to navigation
Jump to search
« previous | Wednesday, September 7, 2011 | next »
Haskell (cont'd)
Type Class
a collection of function signatures that a type must satisfy in order to be a member of the class (similar to a Java interface
class Eq a where
(==), (/=) :: a -> a -> Bool
class Eq a => Ord a where
(<), (<=), (>), (>=) :: a -> a -> Bool
min, max :: a -> a -> a
Examples of usage in function type declarations
elem :: Eq a => a -> [a] -> Bool
min :: Ord a => a -> a -> a
Where Eq and Ord are type classes
Show and Read
class Show a where
show :: a -> String
class Read a where
read :: String -> a
Read needs type annotations in some uses so that Haskell knows what to read into:
> read "10" :: Int
10
> read ("[1, 2, 3]") :: [Int]
[1,2,3]
> map (* 2.0) (read ("[1, 2]")
[2.0,4.0]
In map's case, map expects a list of types acceptable to a function. The * operator expects two arguments of the same type. Since one type is given in the curried function (* 2.0), Haskell can infer the type that the read function is supposed to return.