2025-10-31 Daily Worksheet

Assorted practice, including Maybe, data, foldl.
  1. Write a function cutter :: String -> Maybe String. It changes str to “xstrx”, except that if str has fewer than 5 letters it becomes Nothing

     cutter s = s
    
     check_cutter = [cutter "Box" == Nothing
                    ,cutter "BigBox" == Just "xBigBoxx" ]
    
  2. Write a recursive function cutmap that begins by applying the cutter to each item in a list. When the result is Nothing, skip that item in the output. When the result is Just str, put str in the output.

     check2 = [ cutmap ["Box", "BigBox"] == ["xBigBoxx"] ]
    
  3. A shopping list [(Int, (String, Double))] has a list of how many of each item to buy, the item name, and the cost.

     shop0 = [(5, ("Apple", 0.75)), (2, ("Cabbage", 0.99))]
    

    Use foldl with a named update function to find the total cost of all items except skip any food with a “g” in the name.

     check_fc = (foldcost shop0 == 3.75)
    
  4. What is the benefit of using (Num a) and not Double in the signature below?

     subtract_posn :: (Num a) => (a,a) -> (a,a) -> (a,a)
     subtract_posn (x0,y0) (x1,y1) = (x0-x1, y0-y1)
    

Data

  1. Use record syntax to create a data type called Welcome that holds a String name, a String gift, and an int level.

     exw = Persona {name="Pomerance", gift="telekinesis", level=4}
    
  2. Write a function enhance :: Persona -> Persona that prepends “strong " to the gift and increases the level by one.

  3. A function partner :: Persona -> (Maybe String) -> Persona might append a new second name.

     partner_tests = [
       partner exw (Just "Smith") ==
           Persona{name="Pomerance Smith",
                   gift="telekinesis",
                   level=4}
      ,partner exw Nothing == exw
     ]
    
Last modified November 4, 2025: Site edits. (e22a750)