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:
IntorString. - 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
Posnhave?Game_Result?
Posn
The first exercises use the familiar ordered pair type.
data Posn = Make_Posn Float Float
deriving (Show, Eq)
-
The function
move_righttakes in a decimal number and aPosn, and puts out a newPosnwhose 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
parabolafunction takes in a decimal x and puts out aPosnwith 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
scorefunction takes in aGame_Resultand puts out anIntthat depends on the input: win(1), lose(-1), or tie(0). Write the signature and function. -
The
opponent_resultfunction takes in aGame_Resultof a team and puts out theGame_Resultof 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
dataline forWYColor. - The
conv1function changesOrangeto'o'andBlueto'b'. Write the signature and function. - The
convfunction changes a list ofWYColorto a string like"bbboobb". Write the signature and function.