An ambiguous type variable resulting from the use of `handle`

In this code:

import System.Posix.Files import Control.Exception safeStat :: FilePath -> IO (Maybe FileStatus) safeStat path = handle (\_ -> return Nothing) (getFileStatus path >>= (return . Just)) 

I get this error (in ghci):

 Ambiguous type variable `e0' in the constraint: (Exception e0) arising from a use of `handle' ... 

I can get rid of the error by encoding something like:

 nothing :: IOException -> Maybe a nothing _ = Nothing safeStat :: FilePath -> IO (Maybe FileStatus) safeStat path = handle (return . nothing) (getFileStatus path >>= (return . Just)) 

What's happening??? I would like hander to handle any exception.

+4
source share
2 answers

Ambiguous type variable means that the compiler cannot use the output type. Because it can be many data types with an instance of an exception typeclass. You can use SomeException to handle any exception. For instance:

 safeStat :: FilePath -> IO (Maybe FileStatus) safeStat path = handle errorHandler $ fmap Just $ getFileStatus path where errorHandler :: SomeException -> IO (Maybe FileStatus) errorHandler _ = return Nothing 
+3
source

You can use the value of SomeException according to the pattern of your lambda function:

 import System.Posix.Files import Control.Exception safeStat :: FilePath -> IO (Maybe FileStatus) safeStat path = handle (\(SomeException _) -> return Nothing) (getFileStatus path >>= (return . Just)) 
+3
source

All Articles