Monad (functional Programming) - Generic Monadic Functions

Generic Monadic Functions

Given values produced by safe division, we might want to carry on doing calculations without having to check manually if they are Nothing (i.e. resulted from an attempted division by zero). We can do this using a "lifting" function, which we can define not only for Maybe but for arbitrary monads. In Haskell this is called liftM2:

liftM2 :: Monad m => (a -> b -> c) -> m a -> m b -> m c liftM2 op mx my = do x <- mx y <- my return (op x y)

Recall that arrows in a type associate to the right, so liftM2 is a function that takes a binary function as an argument and returns another binary function. The type signature says: If m is a monad, we can "lift" any binary function into it. For example:

(.*.) :: (Monad m, Num a) => m a -> m a -> m a x .*. y = liftM2 (*) x y

defines an operator (.*.) which multiplies two numbers, unless one of them is Nothing (in which case it again returns Nothing). The advantage here is that we need not dive into the details of the implementation of the monad; if we need to do the same kind of thing with another function, or in another monad, using liftM2 makes it immediately clear what is meant (see Code reuse).

Mathematically, the liftM2 operator is defined by:

Read more about this topic:  Monad (functional Programming)

Famous quotes containing the words generic and/or functions:

    “Mother” has always been a generic term synonymous with love, devotion, and sacrifice. There’s always been something mystical and reverent about them. They’re the Walter Cronkites of the human race . . . infallible, virtuous, without flaws and conceived without original sin, with no room for ambivalence.
    Erma Bombeck (20th century)

    The mind is a finer body, and resumes its functions of feeding, digesting, absorbing, excluding, and generating, in a new and ethereal element. Here, in the brain, is all the process of alimentation repeated, in the acquiring, comparing, digesting, and assimilating of experience. Here again is the mystery of generation repeated.
    Ralph Waldo Emerson (1803–1882)