Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using 'Either' in Haskell

I have two values, t1 and t2, of type Either String Type. The Left-value is used for error handling. These values are used in a function which returns Either String Type.

What I want to do is check if both t1 and t2 are Right-values and satisfy p :: Type -> Bool. If they do, I want to return Right (the type inside t1). If both t1 and t2 are Right-values, but do not satisfy p, I want to return Left someString. If one of t1 or t2 is a Left value, I just want to pass on that value.

How can I do this in an elegant way? I have a hunch that using Either as a monad is the right thing to do, but I'm not sure of how to go about it.

like image 603
Viktor Dahl Avatar asked Jun 09 '11 09:06

Viktor Dahl


1 Answers

Why monads?

test p (Right t1) (Right t2) | p t1 && p t2 = Right t1
                             | otherwise = Left "nope"
test _ (Left t1) _ = Left t1
test _ _ (Left t2) = Left t2
like image 90
Landei Avatar answered Oct 06 '22 03:10

Landei