Skip to content

Instantly share code, notes, and snippets.

@nishanths
Last active May 9, 2021 14:50
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 nishanths/60a8d90d36d360c0c829f387f22ba0fb to your computer and use it in GitHub Desktop.
Save nishanths/60a8d90d36d360c0c829f387f22ba0fb to your computer and use it in GitHub Desktop.
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