Gu

Guards in Elixir

53 exercises

About Guards

Guards are used as a complement to pattern matching. They allow for more complex checks. They can be used in some, but not all situations where pattern matching can be used, for example in function clauses or case clauses.

def empty?(list) when is_list(list) and length(list) == 0 do
  true
end
  • Guards begin with the when keyword, followed by a boolean expression.

  • Guard expressions are special functions which:

    • Must be pure and not mutate any global states.
    • Must return strict true or false values.
  • A list of common guards are found in the Elixir documentation. They include:

  • You can define your own guard with defguard.

    • According to Elixir's naming convention, guard names should start with is_.

      defmodule HTTP do
        defguard is_success(code) when code >= 200 and code < 300
      
        def handle_response(code) when is_success(code) do
          :ok
        end
      end
      
Edit via GitHub The link opens in a new window or tab

Learn Guards

Practicing is locked

Unlock 6 more exercises to practice Guards