Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create new guard clause

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
like image 876
Christian Di Lorenzo Avatar asked Jan 21 '14 15:01

Christian Di Lorenzo


People also ask

What is a guard clause in coding?

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.

Should you use guard clauses?

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.

Where should you put a guard clause in a method?

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.

Are guard clauses good practice?

The use of guard clauses is a good practice to avoid unnecessary branching, and thus make your code more lean and readable.


1 Answers

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

like image 117
José Valim Avatar answered Sep 26 '22 03:09

José Valim