Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure maps in a monad

Tags:

haskell

monads

Suppose I have two functions

f :: Monad m => a -> m a
g :: a -> a

that I want to consecutively apply to some element like so:

(return x) >>= f >>= g

This doesn't work because g is pure, so I first need to "artificially" turn it monadic. One possibility is

(return x) >>= f >>= (return . g)

which isn't very intuitive to me. Another possibility is to use that a Monad is Applicative:

(return g) <*> ((return x) >>= f)

But this is not very intuitive because of the different order of function and argument:

(>>=) :: Monad m => m a -> (a -> m b) -> m b
(<*>) :: Applicative f => f (a -> b) -> f a -> f b

What is the canonical way to deal with this? If (>>==) = (flip ((<*>) . pure)) one can write ((pure x) >>= f) >>== g, which would be fine except for operator precedence. Of course pure functions in monadic code are a common thing so surely there is a standard way to deal with them?

Edit: I didn't say this originally but I was thinking of a situation where I had several functions, some pure, some monadic, and I wanted to apply them in some random order.

like image 802
Stefan Witzel Avatar asked Nov 30 '22 07:11

Stefan Witzel


2 Answers

What you here describe is fmap :: Functor f => (a -> b) -> f a -> f b. Furthermore since pure x >>= f should be the same as f x, we thus can simplify the given expression to:

fmap g (f x)

or we can make use of the infix alias (<$>) :: Functor f => (a -> b) -> f a -> f b:

g <$> f x
like image 158
Willem Van Onsem Avatar answered Dec 05 '22 04:12

Willem Van Onsem


I think the most straightforward solution is Kleisli composition >=> from Control.Monad module.

Since both >=> and (.) are right-associative and (.) has higher precedence, you can write the following:

-- (>=>) :: Monad m => (a -> m b) -> (b -> m c) -> (a -> m c)

f :: Monad m => a -> m a
g :: a -> a
h :: Monad m => a -> m b
j :: b -> b

q :: Monad m => a -> m b
q  =  f >=> return . g >=> h >=> return . j
--       |         |- Use (return .) to transform (a -> b) into (a -> m b)
--       |- Use Kleisli composition >=> to compose Kleisli arrows, i.e.
--       |-   the functions going from values to monadic values, (a -> m b)
like image 28
lsmor Avatar answered Dec 05 '22 05:12

lsmor