8. Constructors

What is the constructor?

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 or String.
  • 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.

  1. Identify the type and value constructors:

     data Posn = Make_Posn Float Float
    
  2. Identify the type and value constructors:

     data Game_Result = Win | Lose | Tie
    
  3. 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)
  1. The function move_right takes in a decimal number and a Posn, and puts out a new Posn 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
    
  2. The parabola function takes in a decimal x and puts out a Posn 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)
  1. The score function takes in a Game_Result and puts out an Int that depends on the input: win(1), lose(-1), or tie(0). Write the signature and function.

  2. The opponent_result function takes in a Game_Result of a team and puts out the Game_Result of their opponent in the last match. Write the signature and function.

  3. 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.

  1. Write the data line for WYColor.
  2. The conv1 function changes Orange to 'o' and Blue to 'b'. Write the signature and function.
  3. The conv function changes a list of WYColor to a string like "bbboobb". Write the signature and function.