When are suitable guard expressions?

Here is an example I wrote that uses if-else branches and security expressions. When is another approach to another? The main reason I want to know this is because languages ​​usually have an idiomatic way of doing things.

 test1 ab = if mod b 30 then a + b else if mod b 50 then a + b else a test2 ab | mod b 3 ≡ 0 = a + b | mod b 50 = a + b | otherwise = a 
+6
haskell idiomatic
source share
2 answers

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

With the guards, you have a very simple and understandable list of conditions and results - very close to how the function will be written by a mathematician.

With if , on the other hand, you have a somewhat complicated (essentially O (n 2 ) reading difficulty) structure of nested expressions with keywords that were selected at irregular intervals.

For simple cases, basically, a toss between if and protection - if can be even more readable in some very simple cases, because it’s easier to write on one line. However, for more complex logic, guards are a much better way to express the same idea.

+11
source share

I always thought it was a matter of preference. Personally, I prefer the latter, I think that if-elses give a more urgent feeling than guards, and I think that guards are easier to read.

+6
source share

All Articles