May 2018
Intermediate to advanced
412 pages
9h 3m
English
We’ve seen that pattern matching allows Elixir to decide which function to invoke based on the arguments passed. But what if we need to distinguish based on the argument types or on some test involving their values? For this, use guard clauses. These are predicates that are attached to a function definition using one or more when keywords. When doing pattern matching, Elixir first does the conventional parameter-based match and then evaluates any when predicates, executing the function only if at least one predicate is true.
| | defmodule Guard do |
| | def what_is(x) when is_number(x) do |
| | IO.puts "#{x} is a number" |
| | end |
| | def what_is(x) when is_list(x) do |
| | IO.puts "#{inspect(x)} is a list" ... |
Read now
Unlock full access