blob: 7420f9217197e67955aa45f184fd27a2f41b4dc2 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
# Lecture 2: Algebraic data types
## Enumeration types
data Thing = Shoe
| Ship
| SealingWax
| Cabbage
| King
derivating Show
The example above is a **type declaration**. The new type is called `Thing` and it has 5 **data constructors** (`Shoe`, `Ship`, etc.). A type's constructors are the only values for that type.
The line that says `deriving Show` is a special instruction that tells the GHC to automatically generate default code for converting a `Thing` to `String`.
Shoe :: Thing
Shoe = Shoe
listO'Things :: [Thing]
listO'Things = [Show, SealingWax, King, Cabbage, King]
Functions on enumeration types can be written using pattern-matching.
isSmall :: Thing -> Bool
isSmall Show = True
isSmall Ship = False
isSmall SealingWax = True
isSmall Cabbage = True
isSmall King = False
Since function clauses are checked from top to bottom, `isSmall` can be rewritten like this:
isSmall2 :: Thing -> Bool
isSmall2 Ship = False
isSmall2 King = False
isSmall2 _ = True
## Beyond enumeration
|