- 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.
- WildFly:New Features
- Spring Cloud Alibaba微服務(wù)架構(gòu)設(shè)計(jì)與開(kāi)發(fā)實(shí)戰(zhàn)
- Hands-On Machine Learning with scikit:learn and Scientific Python Toolkits
- JavaScript+DHTML語(yǔ)法與范例詳解詞典
- R語(yǔ)言經(jīng)典實(shí)例(原書(shū)第2版)
- 架構(gòu)不再難(全5冊(cè))
- Mastering Spring MVC 4
- Raspberry Pi for Secret Agents(Third Edition)
- Android Native Development Kit Cookbook
- Python時(shí)間序列預(yù)測(cè)
- C#實(shí)踐教程(第2版)
- C語(yǔ)言程序設(shè)計(jì)
- Android項(xiàng)目實(shí)戰(zhàn):手機(jī)安全衛(wèi)士開(kāi)發(fā)案例解析
- HTML+CSS+JavaScript網(wǎng)頁(yè)設(shè)計(jì)從入門(mén)到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開(kāi)發(fā)視頻大講堂)
- 視窗軟件設(shè)計(jì)和開(kāi)發(fā)自動(dòng)化:可視化D++語(yǔ)言