[Haskell-cafe] Just 3 >>= (1+)?

Austin Seipp mad.one at gmail.com
Sat May 9 16:56:23 EDT 2009


Excerpts from michael rice's message of Sat May 09 14:31:20 -0500 2009:
> Why doesn't this work?
> 
> Michael
> 
> ================
> 
> data Maybe a = Nothing | Just a
> 
> instance Monad Maybe where
>     return         = Just
>     fail           = Nothing
>     Nothing  >>= f = Nothing
>     (Just x) >>= f = f x
>     
> instance MonadPlus Maybe where
>     mzero             = Nothing
>     Nothing `mplus` x = x
>     x `mplus` _       = x
> 
> ================
> 
> [michael at localhost ~]$ ghci
> GHCi, version 6.10.1: http://www.haskell.org/ghc/  :? for help
> Loading package ghc-prim ... linking ... done.
> Loading package integer ... linking ... done.
> Loading package base ... linking ... done.
> Prelude> Just 3 >>= (1+)
> 
> <interactive>:1:0:
>     No instance for (Num (Maybe b))
>       arising from a use of `it' at <interactive>:1:0-14
>     Possible fix: add an instance declaration for (Num (Maybe b))
>     In the first argument of `print', namely `it'
>     In a stmt of a 'do' expression: print it
> Prelude> 
> 

Look at the types:

    Prelude> :t (>>=)
    (>>=) :: (Monad m) => m a -> (a -> m b) -> m b
    Prelude> :t (+1)
    (+1) :: (Num a) => a -> a
    Prelude> 

The return type of '(+1)' in this case should be 'm b' but it instead
only returns 'b'. If we tag a return on there, it will work fine:

    Prelude> Just 3 >>= return . (+1)
    Just 4
    Prelude> 

Austin


More information about the Haskell-Cafe mailing list