Skip to content

Instantly share code, notes, and snippets.

@jisantuc
Created April 27, 2018 18:31
Show Gist options
  • Save jisantuc/2e5ae4e60d1088bc7c5adc6637e4a3bd to your computer and use it in GitHub Desktop.
Save jisantuc/2e5ae4e60d1088bc7c5adc6637e4a3bd to your computer and use it in GitHub Desktop.
module FiveMinuteFP where
data Option a = Nope | Yup a deriving (Eq, Show)
-- try to make a number odd by adding 1 to it
oddify1 :: Int -> Option Int
oddify1 x =
case (x `mod` 2) of
0 -> Yup (x + 1)
_ -> Nope
-- try to make a number odd by adding 2 to it
oddify2 :: Int -> Option Int
oddify2 x =
case (oddify1 x) of
Nope -> Yup (x + 2)
(Yup _) -> Nope
instance Functor Option where
fmap f Nope = Nope
fmap f (Yup a) = Yup (f a)
instance Applicative Option where
pure a = Yup a
(<*>) Nope _ = Nope
(<*>) (Yup f) Nope = Nope
(<*>) (Yup f) (Yup a) = Yup (f a)
instance Monad Option where
return = pure
(>>=) Nope f = Nope
(>>=) (Yup a) f = f a
-- fmap examples
(+1) <$> Yup 3
-- fails since the function ends up in the context; need the applicative
(+) <$> Yup 3 <$> Yup 4
-- chaining with more structure
oddify1 <$> oddify1 2
oddify1 2 >>= oddify2
oddify1 2 >>= oddify2 >>= oddify2 >>= oddify2 >>= oddify2 >>= oddify2 >>= oddify2
-- applicative examples
:t (+) <$> Yup 3
(+) <$> Yup 3 <*> Yup 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment