views:

209

answers:

2

Here is an example I wrote that uses if-else branches and guard expressions. When is one more appropriate over the other? The main reason I want to know this is because languages typically have a idiomatic way of doing things.

test1 a b =
    if mod b 3 ≡ 0 then a + b
    else if mod b 5 ≡ 0 then a + b
    else a

test2 a b 
    | mod b 3 ≡ 0 = a + b
    | mod b 5 ≡ 0 = a + b
    | otherwise = a
+5  A: 

I always thought it was a matter of preference. Personally, I prefer the second one, I think that the if-elses give a more imperative feel than the guards, and I find the guards easier to read.

sabauma
I really do like the way the guards read.
ChaosPandion
+11  A: 

The example you give is a very good demonstration of how guards are better.

With the guards, you have a very simple and readable list of conditions and results — very close to how the function would be written by a mathematician.

With if, on the other hand, you have a somewhat complicated (essentially O(n2) reading difficulty) structure of nested expressions with keywords thrown in at irregular intervals.

For simple cases, it's basically a toss-up between if and guards — if might even be more readable in some very simple cases because it's easier to write on a single line. For more complicated logic, though, guards are a much better way of expressing the same idea.

Chuck
+1 for, apart from being right, "O(n²) reading difficulty"
delnan
@delnan - Maybe they were thinking *"O(n²) signal noise to ratio"* with `n` being the number of conditions.
ChaosPandion