Last active
May 9, 2021 14:50
-
-
Save nishanths/60a8d90d36d360c0c829f387f22ba0fb to your computer and use it in GitHub Desktop.
Functors, Applicatives, Monads: https://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html
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
main = do | |
firstName <- getLine | |
print firstName | |
-- Functors apply a function that takes a value and returns a value to a | |
-- wrapped value. | |
class Functor c where | |
fmap :: (a -> b) -> c a -> c b | |
($) :: c a -> (a -> b) -> c b | |
instance Functor Maybe where | |
fmap fn (Just val) = Just (fn val) | |
fmap fn Nothing = Nothing | |
instance Functor [] where | |
fmap = map | |
instance Functor ((->) r) where | |
fmap f g = f . g | |
-- Applicatives apply a wrapped function that takes a value and returns a | |
-- value to a wrapped value. | |
-- | |
-- This helps when the original unwrapped function takes multiple wrapped | |
-- arguments, which after the first argument is applied, causes the original | |
-- unwrapped function to be become a wrapped function. | |
class Applicative c where -- c is Functor | |
ap :: c (a -> b) -> c a -> c b | |
(*) :: c a -> c (a -> b) -> c b | |
instance Applicative Maybe where | |
ap Nothing _ = Nothing | |
ap (Just fn) v = fn ($) v -- reuse fmap | |
-- Monads apply a function that takes a value and returns a wrapped value to a | |
-- wrapped value. | |
class Monad c where -- c is Applicative Functor | |
bind :: (a -> c b) -> c a -> c b | |
(>>=) :: c a -> (a -> c b) -> c b | |
instance Monad Maybe where | |
Nothing >>= fn = Nothing | |
Just val >>= fn = fn val | |
half :: Integral a => a -> Maybe a | |
half x = if even x | |
then Just (x `div` 2) | |
else Nothing | |
Just 20 >>= half >>= half >>= half |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment