Kembali ke Perpustakaan
Region:
Switch to EN
Menengah Exercism • elixir
Guards
Ringkasan Pelajaran
# Introduction
About
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
whenkeyword, followed by a boolean expression. -
Guard expressions are special functions which:
- Must be pure and not mutate any global states.
- Must return strict
trueorfalsevalues.
-
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
-
Originally from Exercism elixir concepts