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 Nothing and 20 plus the value when given a 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 a Just number, leaving the Nothings alone.

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

     check6 = [evilswap (Just 10) == Nothing,
               evilswap (Just 50) == Nothing,
               evilswap Nothing == Just 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 22, 2024: Changes per bug #3 by AK. (7ad6cd9)