October 2014
Intermediate to advanced
280 pages
7h 20m
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 their types or on some test involving their values? For this, you 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.
| mm/guard.exs | |
| | 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" |
| | end |
| | |
Read now
Unlock full access