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'm getting 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 doding something like:
nothing :: IOException -> Maybe a
nothing _ = Nothing
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path =
handle (return . nothing) (getFileStatus path >>= (return . Just))
What's going on??? I'd like the hander to handle any exception.
Ambiguous type variable
means that compiler can't inference type. Because it can be many of datatypes with instance of Exception typeclass. You can use SomeException for handling any exception. For example:
safeStat :: FilePath -> IO (Maybe FileStatus)
safeStat path = handle errorHandler $ fmap Just $ getFileStatus path
where
errorHandler :: SomeException -> IO (Maybe FileStatus)
errorHandler _ = return Nothing
You can use SomeException
value in pattern matching 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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With