GHC compilation error that occurs when importing a Control.Exception

Ongoing checkpoints while trying to learn Haskell.

I follow Real World Haskell, and when it comes to getting one of their complex examples, I get the following error:

"An ambiguous variable of type e' in the constraint: GHC.Exception.Exception e 'arising from the use of` handle' in FoldDir.hs: 88: 14-61 Probable fix: add a type signature that corrects these type variables "

My corresponding code bits:

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

How to fix this error?

+5
source share
3 answers

-, , .

,

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

ScopedTypeVariables:

{-# LANGUAGE ScopedTypeVariables #-}
import Control.Exception (handle, SomeException)
maybeIO act = handle (\(_ :: SomeException) -> return Nothing) (Just `liftM` act)
+14

Control.Exception GHC 6.10 .

import Control.Exception (bracket, handle)

import Control.OldException (bracket, handle)
+1

Control.OldException . , . maybeIO

perhaps ∷ forall a. IO a → IO (Maybe a)
perhaps task = do
  result ← (try ∷ IO a → IO (Either IOException a)) task
  return $ either (const Nothing) Just result

You must specify an explicit forallone to bring the type variable ainto scope, and -XExplicitForAlluse the GHC compiler flag explicitly forall. You cannot give a trytype in clear text without receiving the error "You cannot specify a type signature for the imported value." If you try type declaration elsewhere, for example. by the result try task, the GHC cannot figure it out. So yes, it's a little awkward for us, strong lawyers, but it gets better.

+1
source

All Articles