How functions pattern match in Elixir

Meryl Dakin
Jan 2 · 5 min read

defmodule Greeter1 do
def hello(%{name: person_name}) do
IO.puts “Hello, “ <> person_name
end
end
Fred
iex> fred = %{
…> name: “Fred”,
…> age: “95”,
…> favorite_color: “Purple”
…> }
# call with entire map
…> Greeter1.hello(fred)
“Hello, Fred”
# call without the key we need returns an error
…> Greeter1.hello(%{age: “95”, favorite_color: “Purple”})
** (FunctionClauseError) no function clause matching in Greeter3.hello/1
The following arguments were given to Greeter3.hello/1:
# 1
%{age: “95”}
iex:12: Greeter3.hello/1
# incoming map
iex> fred = %{
…> name: “Fred”,
…> age: “95”,
…> favorite_color: “Purple”
…> }
%{name: person_name}
%{name: person_name} = %{name: “Fred”, age: “95”, favorite_color: “Purple”}
defmodule Greeter2 do
def hello(%{name: person_name} = person) do
IO.puts “Hello, “ <> person_name
IO.inspect person
end
end
person = %{name: “Fred”, age: “95”, favorite_color: “Purple”}
%{name: person_name} = %{name: “Fred”, age: “95”, favorite_color: “Purple”}
Fred being pattern matched
# call with entire person
…> Greeter2.hello(fred)
“Hello, Fred”
%{age: “95”, favorite_color: “Purple”, name: “Fred”}
# call with only the name key
…> Greeter4.hello(%{name: “Fred”})
“Hello, Fred”
%{name: “Fred”}
# call without the name key
…> Greeter4.hello(%{age: “95”, favorite_color: “Purple”})
** (FunctionClauseError) no function clause matching in Greeter2.hello/1
The following arguments were given to Greeter2.hello/1:
# 1
%{age: “95”, favorite_color: “Purple”}
iex:15: Greeter2.hello/1
defmodule Greeter3 do
def hello(person = %{name: person_name}) do
IO.puts “Hello, “ <> person_name
IO.inspect person
end
end
# call with same old Fred
…> Greeter3.hello(fred)
“Hello, Fred”
%{age: “95”, favorite_color: “Purple”, name: “Fred”}


Footer top
Footer bottom

Flatiron Labs

We're the technology team at The Flatiron School (a WeWork company). Together, we're building a global campus for lifelong learners focused on positive impact.

Meryl Dakin

Written by

Software Developer at the Flatiron School https://github.com/meryldakin http://www.linkedin.com/in/meryldakin/

Flatiron Labs

We're the technology team at The Flatiron School (a WeWork company). Together, we're building a global campus for lifelong learners focused on positive impact.