Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell way to do error checking of multiple items with abort

Tags:

haskell

What is a good way for a Haskell function to check a number of different conditions and return an error message on a failure?

In Python or similar language, it would be straightforward:

if failure_1:
    return "test1 failed"
if failure_2:
    return "test2 failed"
...
if failure_n:
    return "testn failed"
do_computation

How do you do this without arbitrarily nested case/if statements in Haskell?

Edit: some of the test conditions may require IO which puts any test results in the IO monad. I believe this puts a kink in a number of solutions.

like image 365
me2 Avatar asked Jan 26 '10 09:01

me2


2 Answers

So, you're stuck inside IO, and you want to check a bunch of conditions without lots of nested ifs. I hope you'll forgive me a digression onto more general problem solving in Haskell by way of answering.

Consider in abstract how this needs to behave. Checking a condition has one of two outcomes:

  • Success, in which case the program runs the rest of the function
  • Failure, in which case the program discards the rest of the function and returns the error message.

Checking multiple conditions can be viewed recursively; each time it runs "the rest of the function" it hits the next condition, until reaching the final step which just returns the result. Now, as a first step to solving the problem, let's break things apart using that structure--so basically, we want to turn a bunch of arbitrary conditions into pieces that we can compose together into a multi-conditional function. What can we conclude about the nature of these pieces?

1) Each piece can return one of two different types; an error message, or the result of the next step.

2) Each piece must decide whether to run the next step, so when combining steps we need to give it the function representing the next step as an argument.

3) Since each piece expects to be given the next step, to preserve uniform structure we need a way to convert the final, unconditional step into something that looks the same as a conditional step.

The first requirement obviously suggests we'll want a type like Either String a for our results. Now we need a combining function to fit the second requirement, and a wrapping function to fit the third. Additionally, when combining steps, we may want to have access to data from a previous step (say, validating two different inputs, then checking if they're equal), so each step will need to take the previous step's result as an argument.

So, calling the type of each step err a as a shorthand, what types might the other functions have?

combineSteps :: err a -> (a -> err b) -> err b
wrapFinalStep :: a -> err a

Well now, those type signatures look strangely familiar, don't they?

This general strategy of "run a computation that can fail early with an error message" indeed lends itself to a monadic implementation; and in fact the mtl package already has one. More importantly for this case, it also has a monad transformer, which means that you can add the error monad structure onto another monad--such as IO.

So, we can just import the module, make a type synonym to wrap IO up in a warm fuzzy ErrorT, and away you go:

import Control.Monad.Error

type EIO a = ErrorT String IO a

assert pred err = if pred then return () else throwError err

askUser prompt = do
    liftIO $ putStr prompt
    liftIO getLine

main :: IO (Either String ())
main = runErrorT test

test :: EIO ()
test = do
    x1 <- askUser "Please enter anything but the number 5: "
    assert (x1 /= "5") "Entered 5"
    x2 <- askUser "Please enter a capital letter Z: "
    assert (x2 == "Z") "Didn't enter Z"
    x3 <- askUser "Please enter the same thing you entered for the first question: "
    assert (x3 == x1) $ "Didn't enter " ++ x1
    return () -- superfluous, here to make the final result more explicit

The result of running test, as you would expect, is either Right () for success, or Left String for failure, where the String is the appropriate message; and if an assert returns failure, none of the following actions will be performed.

For testing the result of IO actions you may find it easiest to write a helper function similar to assert that instead takes an argument of IO Bool, or some other approach.

Also note the use of liftIO to convert IO actions into values in EIO, and runErrorT to run an EIO action and return the Either String a value with the overall result. You can read up on monad transformers if you want more detail.

like image 188
C. A. McCann Avatar answered Oct 22 '22 13:10

C. A. McCann


Generally pattern matching is a much better way to go than lots of if statements, and checking error conditions is no exception:

func :: [Int] -> Either String Int
func []    = Left "Empty lists are bad"
func [x]
   | x < 0 = Left "Negative? Really?"
   | odd x = Left "Try an even number"
func xs    = Right (length xs)

This function returns either an error message or the length of the parameter. The error cases are tried first and only if none of them match the last case is executed.

like image 30
sth Avatar answered Oct 22 '22 12:10

sth