mirror of
https://github.com/thma/LtuPatternFactory.git
synced 2024-12-02 08:33:20 +03:00
Improve the NullObject example
This commit is contained in:
parent
57cdfd7554
commit
f0946de2e1
@ -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
|
Loading…
Reference in New Issue
Block a user