In Elixir, how would I go about creating a new guard clause for a function? Obviously, I've seen that you can't just call any function in a when
statement, but it would be nice to be able to do something like this:
defmodule Player do
def play_card(player), do: []
def play_card(player) when has_cards(player), do: ...
# Define has_cards as guard clause?
end
Regardless of which programming language is used, a guard clause, guard code, or guard statement, is a check of integrity preconditions used to avoid errors during execution. A typical example is checking that a reference about to be processed is not null, which avoids null-pointer failures.
Guard clause is a good idea because it clearly indicates that current method is not interested in certain cases. When you clear up at the very beginning of the method that it doesn't deal with some cases (e.g. when some value is less than zero), then the rest of the method is pure implementation of its responsibility.
A Guard Clause, also known as Early Return or Bouncer Pattern, is a common practice in programming, consisting in an early exit of a function based on preconditions check.
The use of guard clauses is a good practice to avoid unnecessary branching, and thus make your code more lean and readable.
The short answer is: you can't.
The long answer is that you can define macros and they will work in guards as long as they are made of valid guards expressions. But that is non-trivial for complex guards so it is better avoided unless you really have to.
The list of valid guards can be found in the getting started guide: http://elixir-lang.org/getting-started/case-cond-and-if.html#expressions-in-guard-clauses
A sample implementation of a "complex" guard macro can be found in Elixir source: https://github.com/elixir-lang/elixir/blob/5d34fcdccd20bf38c4f2a13f8adeb78e22b4e74c/lib/elixir/lib/kernel.ex#L1574
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With