Do you want to pick up from where you left of?

# 集合

## 串列 (Lists)

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

Elixir 的串列是用單向連結串列實作的。 這意味著取得串列長度會是一個線性時間 `O(n)` 的運算。 由於同樣的原因，通常把新元素插入串列的頭部 (prepend) 會比插入串列的尾部 (append) 更快：

``````iex> list = [3.14, :pie, "Apple"]
[3.14, :pie, "Apple"]
# Prepending (fast)
iex> ["π" | list]
["π", 3.14, :pie, "Apple"]
# Appending (slow)
iex> list ++ ["Cherry"]
[3.14, :pie, "Apple", "Cherry"]``````

### 串列結合 (List Concatenation)

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

### 串列減法 (List Subtraction)

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

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

``````iex> [2] -- [2.0]
[2]
iex> [2.0] -- [2.0]
[]``````

### 頭 / 尾 (Head / Tail)

``````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"]``````

## 元組 (Tuples)

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

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

## 關鍵字串列 (Keyword lists)

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

• 鍵 (Keys) 為 atoms。
• 鍵 (Keys) 為有序。
• 鍵 (Keys) 不必為唯一。

## 映射 (Maps)

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

``````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.hello
"world"``````

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

：此語法僅能更新映射中已存在的鍵！如果鍵不存在，將會拋出一個 `KeyError` 錯誤。

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