Skip to content

Commit

Permalink
Enhance the guard guide (elixir-lang#5782)
Browse files Browse the repository at this point in the history
Explain the difference between multiple guard clauses and boolean expression
guards in case of failing expressions.
  • Loading branch information
michalmuskala authored and josevalim committed Feb 17, 2017
1 parent 5dd1fec commit 9d2263a
Showing 1 changed file with 29 additions and 1 deletion.
30 changes: 29 additions & 1 deletion lib/elixir/pages/Guards.md
Original file line number Diff line number Diff line change
Expand Up @@ -191,4 +191,32 @@ def foo(_other) do
end
```

The two forms are exactly the same semantically but there are cases where the latter one may be more aesthetically pleasing.
For most cases, the two forms are exactly the same. However, there exists a subtle difference in the case of failing guards, as discussed in the section above.
In case of a boolean expression guard, a failed element means the whole guard fails. In case of multiple guards it means the next one will be evaluated.
The difference can be highlighted with an example:

```elixir
def multiguard(value)
when map_size(value) < 1
when tuple_size(value) < 1 do
:guard_passed
end
def multiguard(_value) do
:guard_failed
end

def boolean(value) when map_size(value) < 1 or tuple_size(value) < 1 do
:guard_passed
end
def boolean(value) do
:guard_failed
end

multiguard(%{}) #=> :guard_passed
multiguard({}) #=> :guard_passed

boolean(%{}) #=> :guard_passed
boolean({}) #=> :guard_failed
```

For cases where guards do not rely on the failing guard behavior the two forms are exactly the same semantically but there are cases where multiple guard clauses may be more aesthetically pleasing.

0 comments on commit 9d2263a

Please sign in to comment.