Monad (functional Programming) - Fmap and Join

Fmap and Join

Although Haskell defines monads in terms of the return and bind functions, it is also possible to define a monad in terms of return and two other operations, join and fmap. This formulation fits more closely with the definition of monads in category theory. The fmap operation, with type (tu) → (M t→M u), takes a function between two types and produces a function that does the "same thing" to values in the monad. The join operation, with type M (M t)→M t, "flattens" two layers of monadic information into one.

The two formulations are related as follows. As before, the ≡ symbol indicates equivalence between two Haskell expressions.

(fmap f) m ≡ m >>= (\x -> return (f x)) join n ≡ n >>= id m >>= g ≡ join ((fmap g) m)

Here, m has the type M t, n has the type M (M r), f has the type tu, and g has the type t → M v, where t, r, u and v are underlying types.

The fmap function is defined for any functor in the category of types and functions, not just for monads. It is expected to satisfy the functor laws:

fmap id = id fmap (f . g) = (fmap f) . (fmap g)

The return function characterizes pointed functors in the same category, by accounting for the ability to "lift" values into the functor. It should satisfy the following law:

return . f = fmap f . return

In addition, the join function characterizes monads:

join . fmap join = join . join join . fmap return = join . return = id join . fmap (fmap f) = fmap f . join

Read more about this topic:  Monad (functional Programming)

Famous quotes containing the word join:

    I ask you to join in a re-United States. We need to empower our people so they can take more responsibility for their own lives in a world that is ever smaller, where everyone counts.... We need a new spirit of community, a sense that we are all in this together, or the American Dream will continue to wither. Our destiny is bound up with the destiny of every other American.
    Bill Clinton (b. 1946)