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:
“Id better get right down to the job.
Its true I dont want to join the Army or turn lathes in
precision parts factories, Im nearsighted and psychopathic anyway.
America Im putting my queer shoulder to the wheel.”
—Allen Ginsberg (b. 1926)