Tomer
Tomer

Reputation: 1229

Applying a function that returns a Monad type to a list using the map function

Say I want to apply a simple function (\x -> x+1) to all elements in the list [1,2,3].

I do map (\x -> x+1) [1,2,3] and get as expected [2,3,4]. The return type is Num a => [a].

Now what happens if my function is returning a Monad type and is defined as \x -> do return x+1? I want to apply this function somehow to all elements in the list and get back a type (Monad m, Num a) => m [a].

And the value will be the same [2,3,4], just wrapped with a Monad.

I've been struggling with this for a while without much progress. Any idea how can I map this function to my list?

Upvotes: 1

Views: 730

Answers (2)

Fyodor Soikin
Fyodor Soikin

Reputation: 80744

There is a monadic version of map - called mapM:

mapM (\x -> return (x+1)) [1,2,3]

Upvotes: 2

MikaelF
MikaelF

Reputation: 3625

You're looking for mapM. You can find it using Hoogle and just typing in

Monad m => (a -> m b) -> [a] -> m [b]

You'll find it in the first few results. The only difference in the type signature is that it's generalized to Traversable:

mapM :: (Traversable t, Monad m) => (a -> m b) -> t a -> m (t b)

With it, you can do things like

> mapM (Just . (+) 1) [1,2,3]
> Just [2,3,4]

Or, a bit less trivial:

> mapM (\x -> if x < 5 then Just x else Nothing) [1..10]
> Nothing

Upvotes: 5

Related Questions