Functors¶
In [1]:
class Functor f where
fmap :: (a -> b) -> f a -> f b
In [2]:
instance Functor Maybe where
-- fmap :: (a -> b) -> Maybe a -> Maybe b
fmap g Nothing = Nothing
fmap g (Just x) = Just (g x)
In [3]:
instance Functor [] where
-- fmap :: (a -> b) -> [a] -> [b]
fmap = map
In [4]:
instance Functor IO where
-- fmap :: (a -> b) -> IO a -> IO b
fmap g mx = do { x <- mx; return (g x) }
Use <$>
Found:
do x <- mx
return (g x)
Why Not:
do g <$> mx
In [5]:
data Tree a = Leaf a | Node (Tree a) (Tree a) deriving Show
instance Functor Tree where
-- fmap :: (a -> b) -> Tree a -> Tree b
fmap g (Leaf x) = Leaf (g x)
fmap g (Node l r) = Node (fmap g l) (fmap g r)
Functor Laws¶
Every valid instance of Functor must obey two fundamental laws:
Identity Preservation: $$\text{fmap id} = \text{id}$$
Composition Preservation: $$\text{fmap } (g \cdot h) = \text{fmap } g \cdot \text{fmap } h$$
Applicatives¶
In [6]:
class Functor f => Applicative f where
pure :: a -> f a
(<*>) :: f (a -> b) -> f a -> f b
In [7]:
instance Applicative Maybe where
-- pure :: a -> Maybe a
pure = Just
-- (<*>) :: Maybe (a -> b) -> Maybe a -> Maybe b
Nothing <*> _ = Nothing
(Just g) <*> mx = fmap g mx
In [8]:
instance Applicative [] where
-- pure :: a -> [a]
pure x = [x]
-- (<*>) :: [a -> b] -> [a] -> [b]
gs <*> xs = [g x | g <- gs, x <- xs]
In [9]:
instance Applicative IO where
-- pure :: a -> IO a
pure = return
-- (<*>) :: IO (a -> b) -> IO a -> IO b
mg <*> mx = do { g <- mg; x <- mx; return (g x) }
Use <$>
Found:
do g <- mg
x <- mx
return (g x)
Why Not:
do g <- mg
g <$> mx
Applicative Laws¶
- Identity:
pure id <*> x = x - Homomorphism:
pure (g x) = pure g <*> pure x - Interchange:
x <*> pure y = pure (\g -> g y) <*> x - Composition:
x <*> (y <*> z) = (pure (.) <*> x <*> y) <*> z
Monads¶
In [10]:
class Applicative m => Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
return = pure
In [11]:
instance Monad Maybe where
-- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= _ = Nothing
(Just x) >>= f = f x
In [12]:
instance Monad [] where
-- (>>=) :: [a] -> (a -> [b]) -> [b]
xs >>= f = [y | x <- xs, y <- f x]
In [13]:
instance Monad IO where
-- (>>=) :: IO a -> (a -> IO b) -> IO b
mx >>= f = do
x <- mx
f x