When I use an imperative language I often write code like
foo (x) {
if (x < 0) return True;
y = getForX(x);
if (y < 0) return True;
return x < y;
}
That is, I check conditions off one by one, breaking out of the block as soon as possible.
I like this because it keeps the code "flat" and obeys the principle of "end weight". I consider it to be more readable.
But in Haskell I would have written that as
foo x = do
if x < 0
then return x
else do
y <- getForX x
if y < 0
then return True
else return $ x < y
Which I don't like as much. I could use a monad that allows breaking out, but
since I'm already using a monad I'd have to lift
everything, which adds words
I'd like to avoid if I can.
I suppose there's not really a perfect solution to this but does anyone have any advice?
Using patterns and guards can help a lot:
You can also introduce small helper functions in a
where
clause. That tends to help readability as well.(Or if the code really is as simple as this example, use logic as FUZxxl suggested).
The best way to do this is using guards, but then you need to have the
y
value first in order to use it in the guard. That needs to be gotten fromgetForX
wich might be tucked away into some monad that you cannot get the value out from except through getForX (for example theIO
monad) and then you have to lift the pure function that uses guards into that monad. One way of doing this is by usingliftM
.For your specific question: How about dangling
do
notation and the usage of logic?Edit
Combined with what hammar said, you can even get more beautiful code:
Isn't it just
EDIT: As Owen pointed out - getForX is monadic so my code above would not work. The below version probably should: