haskellsyntaxoperatorsmonadsfree-monad

Understanding the use of bind in free monad


I'm trying to get how free monads are working. During this I get into the monad instance of Free, which is:

data Free f a = Pure a | Free (f (Free f a))

instance (Functor f) => Monad (Free f) where
  return = Pure
  Pure a >>= k = k a
  Free m >>= k = Free ((>>= k) <$> m)

Knowing that

  -- k :: a -> Free f b
  -- m :: f (Free f a)
  -- fmap :: Functor f => (a -> b) -> f a -> f b
  -- (>>=) :: Free f a -> (a -> Free f b) -> Free f b

I can't get how this is working

Free ((>>= k) <$> m)

First of all how >>= k is even possible? k is a function and the first argument of >>= is not. It's like it bypasses the first argument and puts k as a second one leaving Free f a -> Free f b

Can anyone help me to get a better understanding of this? Thanks!


Solution

  • I don't know what this Free exactly is, however we both know that

    (>>= k) <$> m == fmap (>>= k) m
    

    so if m == f sth, then

    fmap (>>= k) m == f ((>>= k) sth) == f (sth >>= k)
    

    so everything seems to typecheck.

    As suggested also in a comment, probably the only think you missed is that (.op. y) passes y as second argument to .op., unlike (.op.) y, which passes it as first argument.