8. Declaring types and classes Flashcards
What is the keyword for declaring a type? Give a simple example
type
i.e. type Pos = (Int, Int)
(must be capital P)
Can the type keyword be used for declaring recursive types?
No, use the ‘data’ keyword
What keyword can be used for declaring new types? Give an example
Data
i.e. data Bool = False | True
How to declare a new type containing of a single argument? Give an example
newtype
i.e. newtype Nat = N Int
Give an example of a recursive type
data Nat = Zero | Succ Nat
How to declare a class? Give an example
class
i.e. class Eq a where
(==), (/=) :: a -> a -> Bool
x /= y = not (x == y)
How to define a type as an instance of a class?
instance Eq Bool where
False == False = True
True == True = True
_ == _ = False
How to make a type an instance of a class?
deriving
data Bool = False | True
deriving (Eq, Ord, Show, Read)