mhn70
mhn70

Reputation: 39

Ocaml's `try ... with` in Haskell

My question: is there any "try with" equivalent in Haskell? Something like this :

try 
{
 head l
}
with 
Failure _ -> []

If the operation in try failed we pattern match the error and do appropriate job in with section?

Upvotes: 1

Views: 208

Answers (3)

dfeuer
dfeuer

Reputation: 48611

In this simple case, you could just use foldr:

foldr const [] l

Or even use pattern matching directly:

case l of
  [] -> []
  x : _ -> x

More generally, using Maybe or Either, as others have suggested, can make for more modular code. You may want to check out the MaybeT and ExceptT types, and the MonadError class, to integrate failure into monadic computations.

Upvotes: 0

Alec
Alec

Reputation: 32319

You should really be avoiding such errors via total functions. Then, if a function can return an error, have its return type be an Either e a where e is the type of the exception and a is the otherwise successful type. If you don't need to pass any information about the exception, you can just return Maybe a.

That said, Control.Exception has some facilities for catching errors via try or catch, at the cost of only being able to do such handling in the IO monad. At GHCi you can see this:

ghci> import Control.Exception
ghci> catch (head []) (\msg -> putStrLn $ "caught: " ++ show (msg :: SomeException))
caught: Prelude.head: empty list

Upvotes: 3

soupi
soupi

Reputation: 1013

You can use functions and total functions to achieve the same thing most of the time. For your example:

fromMaybe [] (listToMaybe l)

Upvotes: 2

Related Questions