Skip to content

Instantly share code, notes, and snippets.

@Sam-Serpoosh
Created December 26, 2014 22:02
Show Gist options
  • Save Sam-Serpoosh/90b2475bcff2439c723d to your computer and use it in GitHub Desktop.
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/)
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