Enumerations
Simple enumerations, such as our color
type in C can be defined as follows:
data Color = Red | Green | Blue
This says that a value of type Color
can be the value Red
, Green
or
Blue
. No other values are permitted. We call Red
, Green
and Blue
data
constructors for the type Color
. This terminology will make sense when we
consider product types next. The important part is that data constructors also
act as patterns in pattern matching:
colorAsString :: Color -> String
colorAsString Red = "red"
colorAsString Green = "green"
colorAsString Blue = "blue"
This does what you'd expect:
>>> data Color = Red | Green | Blue
>>> :{
| colorAsString Red = "red"
| colorAsString Green = "green"
| colorAsString Blue = "blue"
| :}
>>> colorAsString Green
"green"
A number of types that would be built right into most languages are defined in
Haskell's standard library. One such type is the Bool
type, which can be
defined as
data Bool = False | True
So a Bool
can be False
or True
, and these are the only two possible
values.
You can check in GHCi that this is indeed how Bool
is defined:
>>> :info Bool
type Bool :: *
data Bool = False | True
-- Defined in ‘GHC.Types’
instance Eq Bool -- Defined in ‘GHC.Classes’
instance Ord Bool -- Defined in ‘GHC.Classes’
instance Enum Bool -- Defined in ‘GHC.Enum’
instance Show Bool -- Defined in ‘GHC.Show’
instance Read Bool -- Defined in ‘GHC.Read’
instance Bounded Bool -- Defined in ‘GHC.Enum’
Ignore the type Bool :: *
part and all the instance
lines. The highlighted
part I want you to notice is that Bool
is indeed defined as
data Bool = False | True
and that it is not built into the language but
defined in GHC.Types
, which is one of the modules in Haskell's standard
library.
Once again, False
and True
are the only two data constructors for the Bool
type, and we can use them as patterns. When discussing
if then else
expressions, we
discussed that
if <expr> then
<this>
else
<that>
is simply syntactic sugar for
case <expr> of
True -> <this>
False -> <that>
This case expression uses True
and False
as patterns.