ARTICLE

Monads as Practical Functionality Providers

From Haskell in Depth by Vitaly Bragilevsky

A teaser: Maybe monad as a line saver

type Name = String type Phone = String type Location = String type PhoneNumbers = [(Name, Phone)] type Locations = [(Phone, Location)]
lookup :: Eq a => a -> [(a, b)] -> Maybe b
locByName :: PhoneNumbers -> Locations -> Name -> Maybe Location locByName pnumbers locs name = lookup name pnumbers >>= flip lookup locs
locByName' :: PhoneNumbers -> Locations -> Name -> Maybe Location locByName' pnumbers locs name = case lookup name pnumbers of                                    Just number -> lookup number locs
Nothing -> Nothing
instance  Monad Maybe  where     (Just x) >>= k      = k x
Nothing >>= _ = Nothing -- ...
readMay :: Read a => String -> Maybe a
doubleStrNumber :: (Num a, Read a) => String -> Maybe a doubleStrNumber s = (*2) <$> readMay s
ghci> doubleStrNumber "21" Just 42
ghci> doubleStrNumber "yy" Nothing
plusStrNumbers :: (Num a, Read a) => String -> String -> Maybe a plusStrNumbers s1 s2 = (+) <$> readMay s1 <*> readMay s2
ghci> plusStrNumbers "3" "5" Just 8
ghci> plusStrNumbers "3" "x" Nothing

--

--

Follow Manning Publications on Medium for free content and exclusive discounts.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Manning Publications

Follow Manning Publications on Medium for free content and exclusive discounts.