Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are guard expressions appropriate?

Tags:

idioms

haskell

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
like image 440
ChaosPandion Avatar asked Aug 16 '10 01:08

ChaosPandion


People also ask

What is a guard expression?

In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question.

What is a loop guard in programming?

The boolean expression, or the loop guard is exactly the same as we would write in an if statement, it's just that this boolean expression is evaluated before every iteration of the loop.

What is a guard in Sysml?

Also known as Conditional transition. A guard is a condition that may be checked when a statechart wants to handle an event. A guard is declared on the transition, and when that transition would trigger, then the guard (if any) is checked. If the guard is true then the transition does happen.


1 Answers

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.

like image 173
Chuck Avatar answered Sep 18 '22 13:09

Chuck