- Mastering Elixir
- André Albuquerque Daniel Caixinha
- 311字
- 2021-08-05 10:42:47
Pattern matching on maps
To use pattern matching on a map, we set our pattern with the key-value pairs we want to match on, as you can see in the following example:
iex> %{"name" => name, "age" => age} = %{"name" => "Gabriel", "age" => 1}
%{"age" => 1, "name" => "Gabriel"}
iex> name
"Gabriel"
iex> age
1
Note that in this case we're matching on all keys of the map, but this isn't necessary–we could just match on age, for instance. However, your pattern may only contain keys that exist on the map that's being matched on, otherwise MatchError will be raised.
Sometimes, you may want to match on the value of a variable, instead of rebinding it to a new value. To this end, you can use the pin operator, represented by the ^ character:
iex> name = "Gabriel"
"Gabriel"
iex> %{name: ^name, age: age} = %{name: "Gabriel", age: 1}
%{age: 1, name: "Gabriel"}
iex> %{name: ^name, age: age} = %{name: "Jose", age: 1}
** (MatchError) no match of right hand side value: %{age: 1, name: "Jose"}
As we can see in the preceding snippet, we have the name variable bound to "Gabriel". We then match a map as we did previously in this section, this time using the contents of the name variable. This is equivalent to using the "Gabriel" literal on the left-hand side. When we're trying to match against a map that has a value different than that of the pinned variable, we get a MatchError, as expected.
- TypeScript入門與實戰
- Go語言高效編程:原理、可觀測性與優化
- NLTK基礎教程:用NLTK和Python庫構建機器學習應用
- C語言程序設計教程(第2版)
- Node.js全程實例
- Cocos2d-x Game Development Blueprints
- Java Web從入門到精通(第2版)
- C++程序設計
- Photoshop智能手機APP界面設計
- C語言程序設計實踐
- Scrapy網絡爬蟲實戰
- Getting Started with Electronic Projects
- Shopify Application Development
- 高性能PHP 7
- Learning Network Programming with Java