views:

71

answers:

2

Continuing roadblocks when trying to learn Haskell.

I am following the "Real World Haskell" and when it comes to getting one of their complex examples to work, I obtain the following error

"Ambiguous type variable e' in the constraint: GHC.Exception.Exception e' arising from a use of `handle' at FoldDir.hs:88:14-61 Probable fix: add a type signature that fixes these type variable(s)"

My relevant bits of code are:

import Control.Exception (bracket, handle)
maybeIO :: IO a -> IO (Maybe a)
maybeIO act = handle (\_ -> return Nothing) (Just `liftM` act)

How do I eradicate this error?

+5  A: 

You need to specify a type for the handler-function's argument, so it knows which kinds of exceptions to handle.

You can either do this by naming the function

import Control.Exception (handle, SomeException)
maybeIO act = handle handler (Just `liftM` act)
    where handler :: SomeException -> IO (Maybe a)
          handler _ = return Nothing

Or by using the ScopedTypeVariables extension:

{-# LANGUAGE ScopedTypeVariables #-}
import Control.Exception (handle, SomeException)
maybeIO act = handle (\(_ :: SomeException) -> return Nothing) (Just `liftM` act)
sepp2k
This provides me both with an answer, and helps in my attempts to learn and understand Haskell.
Chris Walton
+1  A: 

Control.Exception exposes a different interface in GHC 6.10 and later. For a quick fix, change

import Control.Exception (bracket, handle)

to

import Control.OldException (bracket, handle)
dhaffey