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

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

Pattern matching on lists

Matching on lists is akin to matching on tuples. Here's a simple example:

iex> [first, second, third] = ["α", "β", "γ"]
["α", "β", "γ"]
iex> first
"α"
iex> second
"β"
iex> third
"γ"

There's nothing new here. What if, for instance, we don't care about the second element of the list? That's where the  _ (underscore) anonymous variable is convenient:

iex> [first, _, third] = ["δ", "ε", "ζ"]
["δ", "ε", "ζ"]
iex> first
"δ"
iex> third
"ζ"

We're again matching a list with three elements, but now bind the second element to the _ variable, which means that we accept anything in that position and we won't use its value.

 

 


The _ variable can never be read from if you do so, you will get a  CompileError:

iex> _
** (CompileError) iex:83: unbound variable _

This way, Elixir is protecting you from inadvertently reading from this variable, which could easily cause unexpected behaviors in your application.

As we've mentioned on the data types section, you can use the hd and tl functions from the Kernel module to get the head and the tail of a list. You can do the same with pattern matching:

iex> [first | rest_of_list] = ["α", "β", "γ"]
["α", "β", "γ"]
iex> first
"α"
iex> rest_of_list
["β", "γ"]

While in this contrived example, this approach yields no benefit, this technique is a fundamental piece to operate on a list using recursion. We'll look at this in greater detail in the Working with collections section.

主站蜘蛛池模板: 济源市| 阿城市| 嘉善县| 金沙县| 新河县| 禹城市| 宜兰县| 澄江县| 黔江区| 遂宁市| 河曲县| 无为县| 昭觉县| 平和县| 龙游县| 乌拉特后旗| 体育| 柳林县| 缙云县| 平阴县| 封丘县| 肇源县| 延吉市| 张家川| 株洲县| 泰来县| 合肥市| 桂阳县| 阿拉善右旗| 西华县| 若羌县| 宝兴县| 中阳县| 紫阳县| 旺苍县| 德江县| 通州市| 武穴市| 丹东市| 定安县| 安溪县|