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

Sebastian Hungerecker sepp2k at googlemail.com
Sun Jun 5 18:31:37 CEST 2011


On 05.06.2011 14:40, Haisheng Wu wrote:
> By looking at sequence implementation in Hugs:
>
> sequence (c:cs) = do x<- c
>       xs<- sequence cs
>       return (x:xs)
>
> Apply it against a list [Just 2, Nothing], we will have:
>    sequence [Just 2, Nothing]
> = do x<- Just 2
>       y<- sequence [Nothing]
>    return (x:y)
> = return (2:Nothing)
>
> The question is
> Why/How `return (2:Nothing)` eval to `Nothing` ?
>    

It doesn't. You went wrong in the last equality there. y doesn't have
the value Nothing, in fact it never gets a value at all.
Let's first look at what sequence [Nothing] evaluates to:

do x <- Nothing
    y <- sequence [Nothing]
    return (x:y)

Since  Nothing >>= f  evaluates to Nothing this means that the above
do-block evaluates to Nothing, too. So  y <- sequence [Nothing]  becomes
y <- Nothing  and again the whole expression evaluates to Nothing and
return (x:y)  never is evaluated.



More information about the Beginners mailing list