2024 Review B

  1. Write an implementation of mapMaybe, which keeps the “Just” results and throws away the “Nothing” results.

         ex1 = mapMaybe chop4 ["dog", "goldmedal", "fish"]
         check1 = (ex1 == ["medal"])
    
         chop4 :: String -> Maybe String
         chop4 s  | length s <= 4  = Nothing
                  | otherwise      = Just (drop 4 s)
    
  2. Stone age functions use pattern matching and recursion, but not list comprehensions or any of the “fancy” machinery. Where possible, they even avoid guards and if statements.

    Write a Stone Age implementation of reverse. Try to avoid using the ++ operator. Stone age definitely means you should not use init or last. (Instead of re-implementing all of the tools you want to use, look for a simpler way using a helper function.)

  3. The class definition for Semigroup looks like this:

     class Semigroup c where
         (<>) :: c -> c -> c
    

    You want to make the following into an instance of semigroup with addition in the first component and multiplication in the second.

     data WorkerL w = WorkerR w w
         deriving (Show, Eq)
    

    Actually you can only do this with a numerical type for w.

  4. (gcfl) One classic Advent of Code problem is to multiply the first and last numbers hidden in a string of “garbage”. For example, given the ex3 below, the numbers are 123, 45, 678 and 9, so the answer would be 123*9, which is 1107.

     ex3 = "garbage123xyz45truck678dark9day"
     check3 = (gcfl ex3 == 123 * 9)
    

    Write gcfl :: String -> Integer.

  5. What is the type signature, including common typeclasses, for each of these?

    1. last

    2. sum

    3. replicate

    4. Average, as defined below.

       average xs = (sum xs) / (fromIntegral len)
           where len = length xs
      
    5. Revjoin:

       revjoin xs ys = (xs ++ [last xs / last ys] ++ ys)
      
  6. Write the data definition for:

  7. a School, which is just like a String

  8. a Studious, including hrs for a decimal number of hours studied, sch for the school they attend, and fd for their main field of interest.

  9. (schrs) Write a signature and the function to find the total number of hours the students at each school study. The output should be a list of (School, Double).

Last modified December 21, 2024: End of semester review and exams. (8a5ce22)