Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous type variable arising 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'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.

like image 275
ErikR Avatar asked Aug 20 '12 00:08

ErikR


2 Answers

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
like image 90
Fedor Gogolev Avatar answered Sep 27 '22 19:09

Fedor Gogolev


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))
like image 45
ДМИТРИЙ МАЛИКОВ Avatar answered Sep 27 '22 19:09

ДМИТРИЙ МАЛИКОВ