O'Reilly logo

Programming Elixir by Dave Thomas

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Pattern Matching and Updating Maps

The question we most often ask of our maps is, “Do you have the following keys (and maybe values)?”

  • Is there an entry with the key :name?

  • Are there entries for the keys :name and :height?

  • Does the entry with key :name have the value "Dave"?

Here’s how we ask these questions using Elixir patterns.

 
iex>​ person = %{ name: ​"Dave"​, height: 1.88 }
 
%{height: 1.88, name: ​"Dave"​}​​
 
iex>​ %{ name: a_name } = person
 
%{height: 1.88, name: ​"Dave"​}​​
 
iex>​ a_name
 
"Dave"​​​
 
iex>​ %{ name: _, height: _ } = person
 
%{height: 1.88, name: ​"Dave"​}​​
 
iex>​ %{ name: ​"Dave"​ } = person
 
%{height: 1.88, name: ​"Dave"​}

Our map does not have the key :weight, so the following pattern match fails:

 
iex>​ %{ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required