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 (t→u) → (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 t → u, 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 . returnIn addition, the join function characterizes monads:
join . fmap join = join . join join . fmap return = join . return = id join . fmap (fmap f) = fmap f . joinRead more about this topic: Monad (functional Programming)
Famous quotes containing the word join:
“The truth is that every intelligent man, as you well know, dreams of being a gangster and ruling over society through violence alone. Since this is not as easy as the novels would have us believe, people generally resort to politics and join the cruelest party.”
—Albert Camus (19131960)