# 群集

## 列表 (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"]
iex> ["π"] ++ list
["π", 3.14, :pie, "Apple"]
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]
``````

### 頭 / 尾 (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)

Elixir 中，映射是使用鍵值的方便選擇 (“go-to” key-value store)。與關鍵字列表不同，它允許任何資料型別做為鍵並且不需排序。你可以用 `%{}` 語法，來定義一個映射：

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