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

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.

主站蜘蛛池模板: 女性| 胶州市| 曲靖市| 洛隆县| 洱源县| 防城港市| 玛纳斯县| 台州市| 永和县| 肇庆市| 邯郸市| 洛川县| 亳州市| 军事| 蓬溪县| 抚顺县| 祁东县| 盐山县| 武义县| 类乌齐县| 石台县| 洞口县| 万源市| 若羌县| 临潭县| 太湖县| 麟游县| 定襄县| 铜陵市| 扬中市| 许昌县| 卫辉市| 甘孜县| 玛纳斯县| 呼伦贝尔市| 巫溪县| 井研县| 滨州市| 龙里县| 金山区| 出国|