diff --git a/src/NullObject.hs b/src/NullObject.hs index bb65368..1c989a1 100644 --- a/src/NullObject.hs +++ b/src/NullObject.hs @@ -1,6 +1,7 @@ module NullObject where import Data.Map (Map, fromList) import qualified Data.Map as Map (lookup) -- avoid clash with Prelude.lookup +import Control.Monad ((>=>)) -- importing the Kleisli 'fish' operator for composing monadic functions type Song = String type Album = String @@ -62,6 +63,10 @@ findUrlFromSong'' :: Song -> Maybe URL findUrlFromSong'' song = findAlbum song >>= findArtist >>= findWebSite +findUrlFromSong''' :: Song -> Maybe URL +findUrlFromSong''' = + findAlbum >=> findArtist >=> findWebSite + nullObjectDemo = do putStrLn "NullObject -> Maybe" @@ -74,4 +79,31 @@ nullObjectDemo = do print $ findUrlFromSong' "An Ending" print $ findUrlFromSong'' "Baby Satellite" + print $ findUrlFromSong''' "A Never Ending Story" + print $ safeRootReciprocal 0 + print $ safeRootReciprocal (-10) + print $ safeRootReciprocal 0.01 + +{-- --This is how >=> could be implemented for Maybe: +(>=>) :: (a -> Maybe b) -> (b -> Maybe c) -> (a -> Maybe c) +m1 >=> m2 = \x -> + case m1 x of + Nothing -> Nothing + Just y -> case m2 y of + Nothing -> Nothing + result@(Just z) -> result +--} + +safeRoot :: Double -> Maybe Double +safeRoot x + | x >= 0 = Just (sqrt x) + | otherwise = Nothing + +safeReciprocal :: Double -> Maybe Double +safeReciprocal x + | x /= 0 = Just (1/x) + | otherwise = Nothing + +safeRootReciprocal :: Double -> Maybe Double +safeRootReciprocal = safeReciprocal >=> safeRoot \ No newline at end of file