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

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].
主站蜘蛛池模板: 辉南县| 文安县| 威远县| 巴彦淖尔市| 华容县| 九江市| 哈巴河县| 连州市| 邳州市| 华坪县| 上犹县| 海伦市| 庆元县| 伊宁市| 县级市| 漳浦县| 高陵县| 华安县| 嘉禾县| 南部县| 甘谷县| 密山市| 黎川县| 郯城县| 九龙坡区| 海原县| 乌恰县| 锡林浩特市| 涿州市| 泽州县| 信宜市| 宕昌县| 绥德县| 石棉县| 荔波县| 永善县| 揭阳市| 友谊县| 大同县| 公主岭市| 根河市|