Created
May 2, 2016 21:21
-
-
Save danyx23/3e87adb8bcf2761644833942cc243237 to your computer and use it in GitHub Desktop.
This file contains 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 MyMaybe a = | |
MyNothing | |
| MyJust a | |
deriving (Show) | |
instance Functor MyMaybe where | |
fmap _ MyNothing = MyNothing | |
fmap f (MyJust a) = MyJust (f a) | |
instance Applicative MyMaybe | |
instance Monad MyMaybe where | |
return = MyJust | |
(>>=) MyNothing _ = MyNothing | |
(>>=) (MyJust a) f = f a | |
maybeAddFive :: MyMaybe Int -> MyMaybe Int | |
maybeAddFive = | |
fmap (+ 5) | |
heavyCalculation1 :: MyMaybe Int -> MyMaybe Int | |
heavyCalculation1 number = do | |
addResult <- (+ 5) <$> number | |
mulResult <- (* addResult) <$> (MyJust 2) | |
return mulResult -- this is actually redundant, see below | |
heavyCalculation2 :: MyMaybe Int -> MyMaybe Int | |
heavyCalculation2 number = do | |
addResult <- (+ 5) <$> number | |
(* addResult) <$> MyJust 2 | |
-- this time with explicit bind instead of do notation | |
heavyCalculation3 :: MyMaybe Int -> MyMaybe Int | |
heavyCalculation3 number = | |
(+ 5) <$> number >>= | |
(\addResult -> (* addResult) <$> MyJust 2) | |
main :: IO () | |
main = do | |
print $ maybeAddFive $ MyJust 2 | |
print $ maybeAddFive MyNothing |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment