Created
December 26, 2014 22:02
-
-
Save Sam-Serpoosh/90b2475bcff2439c723d to your computer and use it in GitHub Desktop.
Implementation of "Kleisli Category" for "Optional" type! (based on the challenge at the end of this article -> http://bartoszmilewski.com/2014/12/23/kleisli-categories/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
data Optional a = Invalid | Valid a | |
deriving (Show) | |
optionalToString :: (Show a) => Optional a -> String | |
optionalToString Invalid = "Not Valid" | |
optionalToString (Valid value) = show value | |
safeRoot :: Double -> Optional Double | |
safeRoot x | |
| x >= 0 = Valid (sqrt x) | |
| otherwise = Invalid | |
safeReciprocal :: Double -> Optional Double | |
safeReciprocal 0 = Invalid | |
safeReciprocal num = Valid (1/num) | |
(>=>) :: (a -> Optional b) -> (b -> Optional c) -> (a -> Optional c) | |
f1 >=> f2 = \x -> | |
let fstResult = f1 x | |
in case fstResult of | |
Valid value -> f2 value | |
Invalid -> Invalid | |
safeRootReciprocal :: Double -> Optional Double | |
safeRootReciprocal = safeReciprocal >=> safeRoot | |
main :: IO () | |
main = putStrLn $ show $ safeRootReciprocal 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment