2025-11-16 Backpack Review

More review exercises covering the fundamentals. Originally from enrichment.
  1. Hand can hold a Left integer or a Right string. Write a data definition for Hand.

  2. Backpack is a data type that holds an Int numPencils, a Double money and a String owner. Write the data definition.

  3. Update the contents of the backpack. If you get a left hand, add the int to the number of pencils. If you get a right hand, set the owner to be the string.

     update :: Backpack -> Hand -> Backpack
    

    Use different methods:

    1. Pattern matching
    2. Updater/accessor functions.
  4. Write a pencil counting function: how many pencils are there total, in all of the backpacks.

     pc :: [Backpack] -> Int
    
    1. List comprehension
    2. Fold
    3. Recursion

Simpler Review Problems

  1. Use map to change a list of words into a list of their lengths.

     q5 ["cat","be"] == [3,2]
    
  2. Use filter to remove all words longer than 6 letters from a list of words.

     q6 ["Workaholic","student","study","now"] == ["study","now"]
    
  3. Use foldl to concatenate all of the strings in a list, except skip “Bob”.

     q7 ["Bob"," ran ","fast"] == " ran fast"
    
Last modified November 21, 2025: Haskell practice and quiz materials. (2542e6b)