Elixir 元组
Elixir 使用大括号 {} 来定义元组。像列表一样,元组可以保存任何值
iex> {:hello,1,2}
{:hello, 1, 2}
iex> {1}
{1}
iex> {}
{}
请注意啊,是 大括号 {} ,不像其它语言,比如 Python3
元组长度
Elixir 提供了 tuple_size/1 函数来获取元组的长度,也就是元组元素的个数
iex> tuple_size({:hello,1,2})
3
iex> tuple_size({1})
1
iex> tuple_size({})
0
获取元组
Elixir 中的元组将元素连续存储在内存中。这意味我们可以通过索引访问元组元素,索引从零 0 开始。
当然了,虽然用的是连续内存存储,这并不意味着我们可以通过索引下标的方式访问元素:
iex> tuple = {:hello,1,2}
{:hello, 1, 2}
iex> tuple[0]
** (FunctionClauseError) no function clause matching in Access.get/3
The following arguments were given to Access.get/3:
# 1
{:hello, 1, 2}
# 2
0
# 3
nil
Attempted function clauses (showing 5 out of 5):
def get(%module{} = container, key, default)
def get(map, key, default) when is_map(map)
def get(list, key, default) when is_list(list) and is_atom(key)
def get(list, key, _default) when is_list(list)
def get(nil, _key, default)
(elixir 1.12.3) lib/access.ex:283: Access.get/3
Elixir 提供了 elem/2 函数来获取一个元组的元素:
iex> tuple = {:hello,1,2}
{:hello, 1, 2}
iex> elem(tuple,1)
1
iex> elem(tuple,2)
2
如果下表超出元组的 长度 -1,那么就会报错
iex> elem(tuple,3)
** (ArgumentError) errors were found at the given arguments:
* 1st argument: out of range
:erlang.element(4, {:hello, 1, 2})
因为是连续内存存储,所以获取元组大小是种 o(n) 的操作
iex> tuple_size({})
0
替换元组元素
元组和列表一样,是不可变的,因此替换元组元素,其实是创建一个新的元组。
Elixir 提供了 put_elem/3 函数替换一个元组的特定位置的元素,并返回一个新元组
iex> tuple = {"我","love",520}
{"我", "love", 520}
iex> tuple = {"我","love",520}
{"我", "love", 520}
iex> cc = put_elem(tuple,1,"爱你")
{"我", "爱你", 520}
iex> tuple
{"我", "love", 520}
iex> cc
{"我", "爱你", 520}
注意: "love" 被替换成了 "爱你"