[Haskell-beginners] Signature of monadic functions

Olivier Iffrig olivier at iffrig.eu
Thu Oct 17 08:34:27 UTC 2013


Lorenzo Tabacchini wrote (2013-10-17 09:30:17 +0200):
> Hi, is there an easy way to transform a function from:
>  Monad m => a -> m b
> to:
>  Monad m => m (a -> b)

No, because there are some functions of type a -> m b which cannot be
expressed as m (a -> b), consider for instance the function

  safeRecip :: Double -> Maybe Double
  safeRecip 0 = Nothing
  safeRecip x = Just $ recip x

You can't turn that function into Maybe (Double -> Double) without
losing information about what happens to 0.

What do you want to do ?

Such "functions" of type m (a -> b) are used in the more general case of
Applicative functors to generalize fmap to functions with more than one
argument. Consider a function
  g :: a -> b -> c
Let's assume you got a Functor f, then you can use fmap to make
  fmap g :: f a -> f (b -> c).
With a Functor, you can't go much further without nesting f's, but with
an Applicative, you have
  (<*>) :: Applicative f => f (a -> b) -> f a -> f b
Control.Applicative also defines (<$>) = fmap, so you can make a
function
  fmap2 :: Applicative f => (a -> b -> c) -> f a -> f b -> f c
  fmap2 g a b = g <$> a <*> b
This is exactly Control.Applicative.liftA2 (or Control.Monad.liftM2).

-- 
Olivier



More information about the Beginners mailing list