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

Daniel Fischer daniel.is.fischer at web.de
Sat May 9 17:03:32 EDT 2009


Am Samstag 09 Mai 2009 21:31:20 schrieb michael rice:
> Why doesn't this work?
>
> Michael
> [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>


The type of (>>=) is Monad m => m a -> (a -> m b) -> m b,
the type of (1 +) is Num n => n -> n.

Using (1 +) as the second argument of (>>=), you must unify
Num n => n -> n 
with
Monad m => a -> m b

the types of the arguments and results must match, so
a = n
m b = n = a
, giving the type
(Monad m, Num (m b)) => m b -> m b

The first argument of (>>=) is Just 3 :: Num k => Maybe k.
That must be unified with m a, giving m = Maybe and a = k. On the other hand we previously 
found a = m b, so in

Just 3 >>= (1 +)

the (1 +) has type
Num (Maybe b) => Maybe b -> Maybe b
and Just 3 has type
Num (Maybe b) => Maybe (Maybe b).
But ghci can't find an instance Num (Maybe b).

You probably wanted

fmap (1 +) (Just 3)
~> Just 4


More information about the Haskell-Cafe mailing list