官术网_书友最值得收藏!

  • Mastering Elixir
  • André Albuquerque Daniel Caixinha
  • 309字
  • 2021-08-05 10:42:46

Pattern matching on tuples

The following snippet shows how pattern matching can be done on tuples:

iex> {number, representation} = {3.1415, "π"}
{3.1415, "π"}
iex> number
3.1415
iex> representation
"π"

The process here is the same as we have described in the preceding snippet. By setting the {number, description} pattern on the left-hand side, we're stating that we expect a tuple with two values—again, if that's not the case, a MatchError will be raised. In this case, the match succeeds, and we can see that the variables number and representation are bound to the expected values.

Unlike Erlang, Elixir allows you to rebind a variable, which is why the following works:

iex> a = 1
1
iex> a = 7
7

However, a variable can only bind once per match:

iex> {a, a} = {3, 3}
{3, 3}
iex> {a, a} = {2, 3}
** (MatchError) no match of right hand side value: {2, 3}

On the first line, the match succeeds because each  a is binding to the same value, 3. On the second line, we get a MatchError because we're binding a to two different values on the same match. Later in this chapter, we'll see how we can make Elixir behave like Erlang in this regard, by using the pin operator.

We can set our expectations even further, using literals on the left-hand side:

iex> {3.1415, representation} = {3.1415, "π"}
{3.1415, "π"}
iex> representation
"π"

Now our expectation is a tuple with two elements, where the first one is the 3.1415 float literal. We can use this on other Elixir types as well, such as lists or maps. This technique becomes even more fruitful when we apply it to functions, as we will see in the next section.

主站蜘蛛池模板: 固阳县| 汝州市| 全椒县| 屏南县| 怀柔区| 邹平县| 宣化县| 即墨市| 鹤庆县| 襄垣县| 湖口县| 栖霞市| 云浮市| 焉耆| 宜城市| 藁城市| 山东省| 秭归县| 广水市| 南丰县| 凤阳县| 邛崃市| 封丘县| 黄浦区| 滦平县| 金川县| 靖安县| 隆子县| 防城港市| 惠东县| 明溪县| 耿马| 黄冈市| 三都| 德昌县| 奉化市| 德安县| 双峰县| 宁蒗| 罗源县| 广州市|