2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

口で言うより行うことがErlang習得への近道と信じています。

リストとは

リストは単純な値の集まりであり、複数の型や一意でない値を含むこともできます。

> L1 = [a, 2, {c, 4}].
[a,2,{c,4}]

> [H|T] = L1.
[a,2,{c,4}]

> H.
a

> T.
[2,{c,4}]

> L2 = [d|T].
[d,2,{c,4}]

> length(L1).
3

Erlangはリストを連結リストとして実装しています。すなわちリストの長さを得るのは線形時間(O(n))の処理となります。そのため、リスト先頭への追加はほとんどの場合にリスト末尾への追加より高速です。

> L3 = [3.14, pie, "Apple"].
[3.14,pie,"Apple"]

% リスト先頭への追加(高速)
> ["π" | L3].
[[960],3.14,pie,"Apple"]

% リスト末尾への追加(低速)
> L3 ++ ["Cherry"].
[3.14,pie,"Apple","Cherry"]

リストの連結には++/2演算子を用います。

> [1, 2] ++ [3, 4, 1].
[1,2,3,4,1]

リストの減算には--/2演算子を用います。存在しない値を引いてしまっても安全です。

> ["foo", bar, 42] -- [42, "bar"].
["foo",bar]

重複した値には注意が必要です。 右側の各要素に対して、最初に出現した要素が左側から削除されます。

> [1, 2, 2, 3, 2, 3] -- [1, 2, 3, 2].
[2,3]

リストの減算の値のマッチには厳密な比較(=:=)が行われています。

% 厳密には型が異なるので減算されない
> [2] -- [2.0].
[2]

% 厳密に同値なので減算される
> [2.0] -- [2.0].
[]

リストを扱う際には、よくリストの頭部(リストの最初の要素)と尾部(残りの要素)を利用したりします。Erlangにはこれらを扱うためのhdtlという2つの便利な関数があります。

> hd([3.14, pie, "Apple"]).
3.14

> tl([3.14, pie, "Apple"]).
[pie,"Apple"]

リストを頭部と尾部に分けるのにパターンマッチやcons演算子(|)を使うこともできます。

> [Head | Tail] = [3.14, pie, "Apple"].
[3.14,pie,"Apple"]

> Head.
3.14

> Tail.
[pie,"Apple"]

Erlangでは文字列もリストとして扱われます。

> [$h, $e, $l, $l, $o] = "hello".
"hello"

> [38360,39746] = "闘魂".
[38360,39746]

リスト操作のための関数はlistsモジュールにあります。

Elixirにも挑戦したい

闘魂ElixirシリーズとElixir Schoolがオススメです。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?