8. Warmups

A few light lifting tasks to get you comfortable with data structures.

These functions are just warmups to be used the first day you learn about data types. We presented solutions to 1 and 3. The fourth wasn’t visible until the first three were done.

  1. (WhoseTurn)

    1. Create a WhoseTurn data type that could be Nobody, Player_A or Player_B.
    2. Write a nextPlayer function that says that after Player A comes Player B, and after Player B comes Player A. If it is nobody’s turn, then the next player is still nobody.
  2. (Rock, Paper, Scissors)

    1. Create a RPS data type that holds the value Rock, Paper, or Scissors.

    2. Write the beats function.

      beats :: RPS -> RPS -> Bool
      beats _ _ = False
      
      check_beats = [Scissors `beats` Paper,
                     Rock `beats` Scissors,
                     Paper `beats` Rock,
                     not (Scissors `beats` Rock)]
      
  3. (Wallet)

    1. A Wallet holds a number of fives ($5 bills) and ones ($1 bills). Create a data type so that both of the following represent a wallet with 8 five dollar bills and 3 one dollar bills.

      a = Wallet 8 3
      b = Wallet {fives=8, ones=3}
      
    2. Create a moreFives :: Wallet -> Int -> Wallet function that increases the number of fives.

       check_moreFives = (moreFives (Wallet 2 8) 3) == Wallet 5 8
      
  4. (Simple updating) Given the data type definition:

     data Sherman = Sherman {a :: Int, b :: Int, c :: String}
       deriving (Show, Eq)
     ex2 = Sherman 10 50 "Them"
    
    1. How do you produce ex3 that is the same as ex2 except the a value is 30?

    2. Produce ex4 that is the same as ex3 except a is 5 and b is 55.

Last modified November 3, 2024: Typesetting fixes. (d9d25fd)