Haskell Custom Data Types
The data keyword defines a new type by listing its constructors: the different forms a value of the type can take. Such types are called algebraic data types (ADTs), and they are the main way to model a problem domain in Haskell.
Enumerations: choices without data
The simplest data type lists a few alternatives, separated by |:
data TrafficLight = Red | Amber | Green
deriving (Show, Eq)
next :: TrafficLight -> TrafficLight
next Red = Green
next Green = Amber
next Amber = Red
canGo :: TrafficLight -> Bool
canGo light = light == Green
main :: IO ()
main = do
print (next Red)
print (take 7 (iterate next Red))
print (map canGo [Red, Amber, Green])Green
[Red,Green,Amber,Red,Green,Amber,Red]
[False,False,True]
TrafficLight is the type; Red, Amber and Green are its constructors (values). Both start with an uppercase letter. Bool itself is defined exactly like this: data Bool = False | True.
deriving (Show, Eq) asks GHC to generate the code for printing and comparing values. Without Show, print (next Red) would not compile.
Constructors with fields
Constructors can carry data. Each constructor lists the types of its fields:
data Shape
= Circle Double -- radius
| Rectangle Double Double -- width, height
| Triangle Double Double Double
deriving Show
area :: Shape -> Double
area (Circle r) = pi * r * r
area (Rectangle w h) = w * h
area (Triangle a b c) = sqrt (s * (s - a) * (s - b) * (s - c))
where
s = (a + b + c) / 2
main :: IO ()
main = do
let shapes = [Circle 1, Rectangle 3 4, Triangle 3 4 5]
print shapes
print (map area shapes)
print (sum (map area shapes))[Circle 1.0,Rectangle 3.0 4.0,Triangle 3.0 4.0 5.0]
[3.141592653589793,12.0,6.0]
21.141592653589793
A constructor is also a function that builds a value: Rectangle :: Double -> Double -> Shape. You can therefore partially apply it or pass it to map:
data Shape = Circle Double | Rectangle Double Double
deriving Show
main :: IO ()
main = do
print (map Circle [1, 2, 3])
print (zipWith Rectangle [1, 2] [10, 20])
let square side = Rectangle side side
print (square 5)[Circle 1.0,Circle 2.0,Circle 3.0]
[Rectangle 1.0 10.0,Rectangle 2.0 20.0]
Rectangle 5.0 5.0
"Sum" and "product" types
| Kind | Example | Read as |
|---|---|---|
| Sum type (alternatives) | data Light = Red | Amber | Green |
a Light is Red or Amber or Green |
| Product type (fields) | data Point = Point Double Double |
a Point is a Double and a Double |
| Both | data Shape = Circle Double | Rectangle Double Double |
either a circle with a radius, or a rectangle with two sides |
With a product type, the type and its single constructor often share a name (Point and Point); that is fine because types and values live in separate namespaces.
The big win of sum types is that the compiler knows all the cases. If you add a constructor later and forget to handle it, -Wall warns you about every function with an incomplete pattern match.
Modelling a domain
Data types make illegal states unrepresentable. A payment is exactly one of these three things, each with exactly the data it needs:
data Payment
= Cash Double
| Card String Double -- last 4 digits, amount
| Voucher String -- a code that covers the full price
deriving Show
describe :: Payment -> String
describe (Cash amount) = "cash " ++ show amount
describe (Card digits amount) = "card ****" ++ digits ++ " for " ++ show amount
describe (Voucher code) = "voucher " ++ code
amountPaid :: Double -> Payment -> Double
amountPaid _ (Cash a) = a
amountPaid _ (Card _ a) = a
amountPaid price (Voucher _) = price
main :: IO ()
main = do
let payments = [Cash 20, Card "4242" 35.5, Voucher "SPRING25"]
mapM_ (putStrLn . describe) payments
print (map (amountPaid 12) payments)cash 20.0
card ****4242 for 35.5
voucher SPRING25
[20.0,35.5,12.0]
Recursive data types
A constructor may contain a value of the type being defined. That is how you build trees, and how the list type itself is defined:
data Tree = Leaf | Node Tree Int Tree
deriving Show
insert :: Int -> Tree -> Tree
insert x Leaf = Node Leaf x Leaf
insert x node@(Node left v right)
| x < v = Node (insert x left) v right
| x > v = Node left v (insert x right)
| otherwise = node
toList :: Tree -> [Int]
toList Leaf = []
toList (Node left v right) = toList left ++ [v] ++ toList right
depth :: Tree -> Int
depth Leaf = 0
depth (Node l _ r) = 1 + max (depth l) (depth r)
main :: IO ()
main = do
let tree = foldr insert Leaf [5, 2, 8, 1, 9, 3]
print (toList tree)
print (depth tree)
print (insert 4 (Node Leaf 3 Leaf))[1,2,3,5,8,9]
4
Node Leaf 3 (Node Leaf 4 Leaf)
foldr insert Leaf [5, 2, 8, 1, 9, 3] inserts from the right, so 3 is the root. A binary search tree in 15 lines, with sorting for free via toList.
Parameterised types
Types can take type parameters, just like functions take value parameters. Here is a tree that can hold any element type:
data Tree a = Leaf | Node (Tree a) a (Tree a)Tree Int, Tree String and Tree (Int, Bool) are now all valid types. The standard Maybe a and Either e a are defined the same way, and you'll meet them in the Maybe & Either lesson.
Test yourself
In data Shape = Circle Double | Square Double, what is Circle?
- A type
- A constructor, which is also a function
Double -> Shape - A type class
- A field name
What does deriving Show give you?
- Faster code
- An automatically written
Showinstance, so values can be printed - Pattern matching
- A default value
Why are sum types safer than using strings like "cash" or "card"?
- They use less memory
- The compiler knows every case and can warn about unhandled ones
- Strings can't be compared
- They are not safer