Problem Set 2

The Maybe type

data Maybe a = Just a | Nothing

instance Show a => Show (Maybe a) where
  show (Just a) = "Just " ++ show a
  show Nothing  = "Nothing"

Build a library of things that can fail

headMay :: [a] -> Maybe a
headMay [] = Nothing
headMay (h:_) = Just h

tailMay :: [a] -> Maybe [a]
tailMay [] = Nothing
tailMay (_:t) = Just t

lookupMay :: Eq a => a -> [(a, b)] -> Maybe b
lookupMay item [] = Nothing
lookupMay item ((k,v):ks)
  | item == k = Just v
  | otherwise = lookupMay item ks

divMay :: (Eq a, Fractional a) => a -> a -> Maybe a
divMay _ 0 = Nothing
divMay n d = Just (n / d)

maximumMay :: Ord a => [a] -> Maybe a
maximumMay [] = Nothing
maximumMay l  = Just (maximum l)

minimumMay :: Ord a => [a] -> Maybe a
minimumMay [] = Nothing
minimumMay l  = Just (minimum l)

Chains of failing computations

Generalizing chains of failures

Chaining variations

Tailprod

Date: 2016-02-13 sab 00:00

Author: Stefano Rodighiero

Created: 2017-07-11 mar 18:10

Validate