Search code examples
haskellmonadsfunctorapplicative

How to define apply in terms of bind?


In Haskell Applicatives are considered stronger than Functor that means we can define Functor using Applicative like

-- Functor
fmap :: (a -> b) -> f a -> f b
fmap f fa = pure f <*> fa

and Monads are considered stronger than Applicatives & Functors that means.

-- Functor
fmap :: (a -> b) -> f a -> f b
fmap f fa = fa >>= return . f

-- Applicative
pure :: a -> f a
pure = return

(<*>) :: f (a -> b) -> f a -> f b
(<*>) = ???  -- Can we define this in terms return & bind? without using "ap" 

I have read that Monads are for sequencing actions. But I feel like the only thing a Monad can do is Join or Flatten and the rest of its capabilities comes from Applicatives.

join :: m (m a) -> m a
-- & where is the sequencing in this part? I don't get it.

If Monad is really for sequencing actions then How come we can define Applicatives (which are not considered to strictly operate in sequence, some kind of parallel computing)?

As monads are Monoids in the Category of endofunctors. There are Commutative monoids as well, which necessarily need not work in order. That means the Monad instances for Commutative Monoids also need an ordering?

Edit: I found an excellent page http://wiki.haskell.org/What_a_Monad_is_not


Solution

  • If Monad is really for sequencing actions then How come we can define Applicatives (which are not considered to strictly operate in sequence, some kind of parallel computing)?

    Not quite. All monads are applicatives, but only some applicatives are monads. So given a monad you can always define an applicative instance in terms of bind and return, but if all you have is the applicative instance then you cannot define a monad without more information.

    The applicative instance for a monad would look like this:

    instance (Monad m) => Applicative m where
       pure = return
       f <*> v = do
          f' <- f
          v' <- v
          return $ f' v'
    

    Of course this evaluates f and v in sequence, because its a monad and that is what monads do. If this applicative does not do things in a sequence then it isn't a monad.

    Modern Haskell, of course, defines this the other way around: the Applicative typeclass is a subset of Functor so if you have a Functor and you can define (<*>) then you can create an Applicative instance. Monad is in turn defined as a subset of Applicative, so if you have an Applicative instance and you can define (>>=) then you can create a Monad instance. But you can't define (>>=) in terms of (<*>).

    See the Typeclassopedia for more details.