7. Intro Ex

Important knowledge: Maybe class, Nothing and Just value. Pattern matching to destructure.

  1. Write good_sqrt :: Float -> Maybe Float that gives Nothing when asked to find the square root of a negative number.

     check1 = [ good_sqrt 16 == Just 4.0,
                good_sqrt (-25) == Nothing ]
    
  2. Write a function cn :: [Maybe Int] -> Int that counts how many Nothing appear in the list.

     check2 = (cn [Just 5, Nothing, Just 4, Nothing, Nothing] == 3)
    
  3. The function tx :: [Maybe Int] -> Int finds the sum of all of the numbers in the list, ignoring the Nothings.

     check3 = (tx [Nothing, Just 10, Just 30, Nothing] == 40)
    
  4. The function ds :: Maybe Int -> Int gives 10 for all Nothings and 20 plus the value for every Just.

     check4 = [ds Nothing == 10, ds (Just 10) == 30,
               ds (Just 70) == 90 ]
    
  5. The function fm :: Maybe Int -> Maybe Int applies the function $f(x)=x^2-24$ to every number, leaving the Nothings alone.

     check5 = [fm (Just 5) == 1, fm Nothing == Nothing,
               fm (Just 8) == 60]
    
  6. Write the function evilswap :: Maybe Int -> Maybe Int that turns Nothings into 666 and turns Just numbers into Nothings.

     check6 = [evilswap (Just 10) == Nothing,
               evilswap (Just 50) == Nothing,
               evilswap Nothing == 666]
    

Info

There are utility functions available after import Data.Maybe. Those include:

  • isNothing
  • isJust
  • mapMaybe

Don’t use them until you can write them yourself.

Last modified October 15, 2023: Changed title. (7f8a871)