Skip to content

Instantly share code, notes, and snippets.

@danyx23
Created May 2, 2016 21:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danyx23/3e87adb8bcf2761644833942cc243237 to your computer and use it in GitHub Desktop.
Save danyx23/3e87adb8bcf2761644833942cc243237 to your computer and use it in GitHub Desktop.
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