2
0

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 5 years have passed since last update.

elixirでリストの中身を検索したかったやつ

Last updated at Posted at 2019-07-15

elixirで

iex> lists
[
  ["1", "a1", "a2", "a3"],
  ["2", "b1", "b2", "b3"],
  ["5", "c1", "c2", "c3"],
  ["8", "d1", "d2", "d3"]
]

的なリストの中身をID(1,2,5,8)で検索したくて、
とりあえず調べながらやってみたやつです。(もっと綺麗なやり方とかあるはず、、、)

コード

defmodule ListFind do
  # id が含まれている list を探す 
  def id_find(id) do
    Enum.find(lists, fn list ->
      Enum.at(list, 0) == Integer.to_string(id)
    end)
  end
  # 探したリストから要素を取り出す
  def data_find(id) do
    case id_find(id) do
      nil -> "nil"
      list -> Enum.at(list, 1)
    end
  end
end

Enum.findEnum.atで、引数で渡したidが含まれるのリストを探し、
caseでidが存在しなかった場合を弾いてEnum.atで抽出。

2
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?