7. Intro Ex
Important knowledge: Maybe class, Nothing and Just value. Pattern
matching to destructure.
-
Write
good_sqrt :: Float -> Maybe Floatthat givesNothingwhen asked to find the square root of a negative number.check1 = [ good_sqrt 16 == Just 4.0, good_sqrt (-25) == Nothing ] -
Write a function
cn :: [Maybe Int] -> Intthat counts how manyNothingappear in the list.check2 = (cn [Just 5, Nothing, Just 4, Nothing, Nothing] == 3) -
The function
tx :: [Maybe Int] -> Intfinds the sum of all of the numbers in the list, ignoring the Nothings.check3 = (tx [Nothing, Just 10, Just 30, Nothing] == 40) -
The function
ds :: Maybe Int -> Intgives 10 for Nothing and 20 plus the value when given a Just.check4 = [ds Nothing == 10, ds (Just 10) == 30, ds (Just 70) == 90 ] -
The function
fm :: Maybe Int -> Maybe Intapplies 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] -
Write the function
evilswap :: Maybe Int -> Maybe Intthat 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:
isNothingisJustmapMaybe
Don’t use them until you can write them yourself.