# 集合

Some contents of this translation may be outdated.
Several patches were applied to the original lesson since the last update.

## 列表

``````iex> [3.14, :pie, "Apple"]
[3.14, :pie, "Apple"]
``````

Elixir 内部用链表实现列表，这表明获取列表长度是 `O(n)` 的操作。同样的原因，在头部插入比在尾部插入要快。

``````iex> list = [3.14, :pie, "Apple"]
[3.14, :pie, "Apple"]
iex> ["π"] ++ list
["π", 3.14, :pie, "Apple"]
iex> list ++ ["Cherry"]
[3.14, :pie, "Apple", "Cherry"]
``````

### 列表拼接

``````iex> [1, 2] ++ [3, 4, 1]
[1, 2, 3, 4, 1]
``````

### 列表减法

`--/2` 操作符支持列表的减法，而且减去不存在的值也是安全的。

``````iex> ["foo", :bar, 42] -- [42, "bar"]
["foo", :bar]
``````

``````iex> [1,2,2,3,2,3] -- [1,2,3,2]
[2, 3]
``````

### 头/尾

``````iex> hd [3.14, :pie, "Apple"]
3.14
iex> tl [3.14, :pie, "Apple"]
[:pie, "Apple"]
``````

``````iex> [head | tail] = [3.14, :pie, "Apple"]
[3.14, :pie, "Apple"]
3.14
iex> tail
[:pie, "Apple"]
``````

## 元组

``````iex> {3.14, :pie, "Apple"}
{3.14, :pie, "Apple"}
``````

``````iex> File.read("path/to/existing/file")
{:ok, "... contents ..."}
{:error, :enoent}
``````

## 关键字列表

``````iex> [foo: "bar", hello: "world"]
[foo: "bar", hello: "world"]
iex> [{:foo, "bar"}, {:hello, "world"}]
[foo: "bar", hello: "world"]
``````

• 键（key）都是原子
• 键（key）是有序的（定义后，顺序不会改变）
• 键（key）不是唯一的

## 图

Elixir 的图（maps）是键值对结构的第一选择，和关键字列表（keywords）不同，图允许任意类型的数据作为键，而且数据并不严格排序。你可以使用 `%{}` 来定义图：

``````iex> map = %{:foo => "bar", "hello" => :world}
%{:foo => "bar", "hello" => :world}
iex> map[:foo]
"bar"
iex> map["hello"]
:world
``````

Elixir 1.2 版本中，也可以把变量作为图的键（key）：

``````iex> key = "hello"
"hello"
iex> %{key => "world"}
%{"hello" => "world"}
``````

``````iex> %{:foo => "bar", :foo => "hello world"}
%{foo: "hello world"}
``````

``````iex> %{foo: "bar", hello: "world"}
%{foo: "bar", hello: "world"}

iex> %{foo: "bar", hello: "world"} == %{:foo => "bar", :hello => "world"}
true
``````

``````iex> map = %{foo: "bar", hello: "world"}
%{foo: "bar", hello: "world"}
iex> %{map | foo: "baz"}
%{foo: "baz", hello: "world"}
iex> map.hello
"world"
``````