3
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 ── 37. lists:search

Last updated at Posted at 2023-01-25

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

lists:search/2

lists:search/2は真理値返す関数を渡し、その関数が真を返すような値がリスト内にある場合、最初に見つかった値に対して {value, 見つかった値}タプルを返します。見つからない場合は false を返します。

search(fun((term) -> boolean), [term]) -> {value, term} | false
search(見つかったら真理値返す関数, リスト) -> {value, 見つかった値} | false
> lists:search(fun (X) -> X rem 2 == 0 end, [1, 2, 3, 4]).
{value,2}

> lists:search(fun (X) -> X < 0 end, [1, 2, 3, 4]).
false

タプルのリストに対して検索する場合はlists:keyfind/3が便利です。

lists:keyfind/3

keyfind(term, integer, [tuple]) -> tuple | false
keyfind(検索ワード, タプルの要素の位置, タプルのリスト) -> 見つかったタプル | false

lists:keyfind/3はタプルのリストを検索します。指定された位置の要素が検索ワードと等しいタプルを探します。該当するタプルが見つかった場合はそのタプルを、そうでない場合はfalseを返します。

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

> L1 = [{"A",10},{"B",20},{"C",30},{"D",40},{"E",50}].

> lists:keyfind("E", 1, L1).
{"E",50}

> lists:keyfind(30, 2, L1).
{"C",30}

> lists:keyfind(123, 2, L1).
false

lists:keysearch/3

lists:keysearch/3という非常に似た関数がありますが、これは後方互換性のために存在しているそうですので忘れてよさそうです。

> lists:keysearch("E", 1, L1).
{value,{"E",50}}

> lists:keysearch(30, 2, L1).
{value,{"C",30}}

lists:keytake/3

lists:keytake/3を使うと見つかった要素だけではなく、見つかった要素が除外されたリストも同時に取得できます。

> lists:keytake("E", 1, L1).
{value,{"E",50},[{"A",10},{"B",20},{"C",30},{"D",40}]}

> lists:keytake(30, 2, L1).
{value,{"C",30},[{"A",10},{"B",20},{"D",40},{"E",50}]}

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

Elixirにも挑戦したい

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

3
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
3
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?