8. Constructors
The goal of these exercises is to understand the meaning of the type constructors and when to use them.
For these exercises we will not follow the usual Haskell pun of using the same name for the type and its constructor.
Type vs Value (Data) Constructors
Official Haskell vocabulary:
- A type constructor makes a type (abstract). Examples:
Int
orString
. - A value constructor makes a value (concrete), like 13 or “value”.
The word “data constructor” is a common synonym for value constructor,
but I suggest beginners avoid it because the data
statement contains
both the type and value constructor.
-
Identify the type and value constructors:
data Posn = Make_Posn Float Float
-
Identify the type and value constructors:
data Game_Result = Win | Lose | Tie
-
How many value constructors does
Posn
have?Game_Result
?
Posn
The first exercises use the familiar ordered pair type.
data Posn = Make_Posn Float Float
deriving (Show, Eq)
-
The function
move_right
takes in a decimal number and aPosn
, and puts out a newPosn
whose x-coordinate is the sum of the number and the old x-coordinate. Write the signature and then the function.move_right :: Float -> Posn -> Posn
-
The
parabola
function takes in a decimal x and puts out aPosn
with coordinates (x,x*x). Write the signature and the function.
Game Result
The Game_Result
type holds win, lose, or tie. This is different
from Posn
because there is no information inside it, so you will
not use the pattern (Game_Result x)
.
data Game_Result = Win | Lose | Tie
deriving (Show, Eq)
-
The
score
function takes in aGame_Result
and puts out anInt
that depends on the input: win(1), lose(-1), or tie(0). Write the signature and function. -
The
opponent_result
function takes in aGame_Result
of a team and puts out theGame_Result
of their opponent in the last match. Write the signature and function. -
What is wrong with this partial function? Find and fix at least two issues.
opponent_result (Game_Result x) = "Lose"
WY Design
The WYColor
type holds either Orange
or Blue
.
- Write the
data
line forWYColor
. - The
conv1
function changesOrange
to'o'
andBlue
to'b'
. Write the signature and function. - The
conv
function changes a list ofWYColor
to a string like"bbboobb"
. Write the signature and function.