2022-12-04 Quiz

Introduction

You are not allowed to use built-in functions from Data.Maybe even if you know how to use them. Sorry, not sorry!

All of the tester code is available in one spot.

Short Answers

  1. (m3) Give the third item in a list. If there is no third item give Nothing.

     m3 :: [Int] -> Maybe Int
    
  2. (op) Find the product of all of the odd-index item in the list. If any of them are Nothing, then give Nothing.

     op :: [Maybe Int] -> Maybe Int
     ck_op = [op [Just 3, Just 4, Just 10, Just 20] == Just 80,
              op [Just 5, Nothing, Just 2, Just 1] == Nothing,
              op [Nothing, Just 5] == Just 5,
              op [Just 7] == Just 1 -- product of 0 things is 1
              ]
    

Intervals

We are going to work with closed intervals on a number line. The interval centered at $x=5$ and extending 2 units in either direction will be represented by the ordered pair (5,2).

  • The number 5 is called the “center” of the interval.

  • The number 2 is called the “radius” of the interval.

  • Other names for this interval in math class are $3 \le x \le 7$ and $[3,7]$.

      type Interval = (Double, Double)
    

There are two questions using intervals.

  1. Given a list of intervals and a point x on the number line, find the interval containing the point x that has x closest to its center. If no interval contains x, give Nothing. If the point x is equally distant to the centers of more than one interval, pick the one with the smallest “radius” (and if the radii match then it does not matter which one you pick).

     closest :: [Interval] -> Double -> Maybe Interval
    
     check_closest = [
         closest [(5,2),(7,1)] 12 == Nothing,
         closest [(5,2),(7,1)] 6.5 == Just (7,1),
         closest [(5,2),(7,1)] 6 == Just (7,1),
         closest [(5,2),(7,2)] 5.5 == Just (5,2)]
    
  2. Suppose you have a function that takes in an interval and produces a Maybe Interval, like this one:

     f :: Interval -> Maybe Interval
     f (center, radius)
          | radius >= 4   = Just (center, radius/2)
          | otherwise     = Nothing
    

    You are being asked to create a function imapper that takes in one of these functions and a list of Intervals, and puts out a list of all of the Interval results of the function, omitting results that are Nothing.

    For example:

     imapper :: (Interval -> Maybe Interval) -> [Interval] -> [Interval]
     check_i = imapper f [(10,8), (20,2), (30,4)] == [(10,4),(30,2)]
    

    Notice that you are not supposed to have Just (10,4) in your answer list.

Last modified August 18, 2023: 2022-2023 End State (7352e87)