I'm new to functional programming (coming from javascript), and I'm having a hard time telling the difference between the two, which is also messing with my understand of functors vs. monads.
Functor:
class Functor f where
fmap :: (a -> b) -> f a -> f b
Monad (simplified):
class Monad m where
(>>=) :: m a -> (a -> m b) -> m b
fmaptakes a function and a functor, and returns a functor.>>=takes a function and a monad, and returns a monad.
The difference between the two is in the function parameter:
fmap-(a -> b)>>=-(a -> m b)
>>= takes a function parameter that returns a monad. I know that this is significant, but I'm having difficulty seeing how this one slight thing makes monads much more powerful than functors. Can someone explain?
(>>=),(=<<). With(g <$>) :: f a -> f b, the functiong :: a -> bhas no influence on thef"wrapping" -- doesn't change it. With(k =<<) :: m a -> m b, the functionk :: a -> m bitself creates the newm"wrapping", so it can change. - Will Ness>>=can do thatfmapcan't do. In my head they're equivalent because I haven't seen an example, which shows that fmap is inadequate. - m0menimap. you can't. but withconcatMap, you can:map (\x->x+1) [1,2,3]vsconcatMap (\x-> [x,x+1|even x]) [1,2,3]). - Will Nessfilteroperation was just a sugary variant ofmap, but just now I've realized that's not even possible. - m0menimap (\x -> [x|even x]) [1,2,3]but it produces[[],[2],[]]and another level of interpretation done byconcatis then needed to make it really afilter. - Will Ness