[Haskell-beginners] I don't understand mapM in mapM id (Just 1, Nothing, Just 3)

Magnus Therning magnus at therning.org
Fri May 20 14:45:20 CEST 2011


On Fri, May 20, 2011 at 02:31:54PM +0200, Kees Bleijenberg wrote:
> I was playing with winghci and I tried:
>  
> mapM id [Just 1, Just 2, Just 3]
> result: Just [1,2,3]
>  
> I don't understand this answer.
>  
> From  <http://members.chello.nl/hjgtuyl/tourdemonad.html#mapM>
> http://members.chello.nl/hjgtuyl/tourdemonad.html#mapM
> mapM mf xs takes a monadic function mf (having type Monad m => (a -> m b))
> and applies it to each element in list xs; the result is a list inside a
> monad. 
>  
> A few things I've found:
> mapM :: (a -> m b) -> [a] -> m [b]
> So in this case: a = Maybe Int (second arg in mapM id [Just1, Just 2, Just
> 3] and b = Int and m = Maybe. So id is :: Maybe Int -> Maybe Int
>  
> mapM id [Just 1, Nothing, Just 3] 
> result: Nothing.
> My first guess for the result: Just [Just 1, Nothing, Just 3]
>  
> when I do: mapM id [1,2,3] I get an error (id has wrong type, which makes
> sense)
>  
> Can somebody explain what is going on here?

You have to types right:

 a = Maybe Int
 m = Maybe
 b = Int

'mapM' is implemented like this:

 mapM f as =  sequence (map f as)

So working through the examples:

  mapM id [Just 1, Just 2, Just 3]
= sequence (map id [Just 1, ...])
= sequence [Just 1, ...] = Just [1, ...]

  mapM id [Just 1, Nothing, Just 3]
= sequence (map id [Just 1, Nothing, ...])
= sequence [Just1, Nothing, ...]
= Nothing

/M

-- 
Magnus Therning                      OpenPGP: 0xAB4DFBA4 
email: magnus at therning.org   jabber: magnus at therning.org
twitter: magthe               http://therning.org/magnus

I invented the term Object-Oriented, and I can tell you I did not have
C++ in mind.
     -- Alan Kay
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 198 bytes
Desc: not available
URL: <http://www.haskell.org/pipermail/beginners/attachments/20110520/fd72fd73/attachment.pgp>


More information about the Beginners mailing list