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

Lists

Lists are created by wrapping the elements we want inside it with square brackets ([ and ]), separating the values with commas. Internally, lists are implemented as singly linked lists, meaning that accessing the elements of a list is a O(n) operation. Lists aren't stored contiguously in memory as arrays in other languages. As with tuples, list elements can be of any type:

iex> [1, :an_atom, 0.5]
[1, :an_atom, 0.5]

We have the ++ and -- operators that are exclusive to lists, and serve to concatenate and subtract lists, respectively:

iex> [0, 1, 1] ++ [2, 3, 5]
[0, 1, 1, 2, 3, 5]
iex> [0, 1, 1] -- [1, 2, 3]
[0, 1]

To check whether a certain element is present in a list, you can use the in operator:

iex> 1 in [0, 1, 1, 2, 3, 5]
true
iex> 99 in [0, 1, 1, 2, 3, 5]
false

To get the head of a list, we use the hd function, whereas to get the tail of a list, we use the tl function:

iex> hd([0, 1, 1, 2, 3, 5])
0
iex> tl([0, 1, 1, 2, 3, 5])
[1, 1, 2, 3, 5]

Notice that the semantic of tail here is the list without its head (which is also a list), and not the last element of a list. We'll be exploring this concept in more depth, along with some more examples on how to work with lists, in the Working with collections section. For reference, you can find a detailed list of operations you can make on lists at https://hexdocs.pm/elixir/List.html.

Appending to a list is a O(n) operation, as we need to traverse the whole list. Prepending to a list is O(1). To prepend an element to a list, you can use the following syntax: [new_element | list].
主站蜘蛛池模板: 鲁甸县| 长治县| 呼和浩特市| 五峰| 北京市| 开原市| 大田县| 岳西县| 武乡县| 香格里拉县| 章丘市| 洪江市| 龙江县| 永胜县| 石楼县| 沙坪坝区| 泰兴市| 时尚| 夏津县| 彰化市| 明溪县| 英山县| 丰宁| 淮南市| 佛山市| 德清县| 盐津县| 昭通市| 双江| 扎赉特旗| 龙海市| 萨迦县| 博乐市| 贡觉县| 天峻县| 华池县| 汽车| 万盛区| 调兵山市| 汪清县| 库尔勒市|