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 ── 18. lists:map

Last updated at Posted at 2023-01-10

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

lists:map/2

map(fun((term) -> term), [term]) -> [term]
map(各要素に対して実行したい処理, リスト) -> 新しいリスト

リストの各要素に対して同じ処理を適用して新しいリストを生成します。

%% 各要素を二乗する

> lists:map(fun(X) -> X * X end, [1, 2, 3]).
[1,4,9]

map関数に馴染みのない方は闘魂Elixirの図を眺めてみるとなんとなく感覚が掴めるかもしれません。

lists:keymap/3

keymap(fun((term) -> term), integer, [tuple]) -> [tuple]
keymap(値を変換する関数, タプルの要素の位置, タプルのリスト) -> 新しいタプルのリスト

タプルのリストに対して同じ処理を適用して新しいリストを生成します。値の変換はタプルの指定された位置の要素に対して行われます。値を変換する処理は関数として与えます。

%% 各要素のキーをアトムから文字列へ変換

> L1 = [{name, "antonio"}, {name, "masa"}].

> lists:keymap(fun (A) -> atom_to_list(A) end, 1, L1).
[{"name","antonio"},{"name","masa"}]

要素の数え方は「1、2、3ぁっダー!」です。例えば最初の要素のインデックスは1となります。

listsモジュールには他にもリスト処理のための関数がたくさんあります。

lists:flatmap/2

map(fun((term) -> term), [term]) -> [term]
map(各要素に対して実行したい処理, リスト) -> 各要素に対する処理の結果が連結された新しいリスト

リストの各要素に対して同じ処理を適用して、新しいリストに連結します。各要素に対して実行したい処理がリストを返す場合に最終結果が入れ子になって欲しくない場合に便利です。

> lists:map(fun(X) -> [X, X] end, [a, b, c]).
[[a,a],[b,b],[c,c]]

> lists:flatmap(fun(X) -> [X, X] end, [a, b, c]).
[a,a,b,b,c,c]

> lists:flatmap(fun(X) -> [[X]] end, [a, b, c]).
[[a],[b],[c]]

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?