6
2

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.

ElixirAdvent Calendar 2021

Day 5

Enumで遊ぼう (with_index,filter,map)

Posted at

Enumで遊んでみたいと思います
今回は
Enum.with_index
Enum.filter
Enum.map
で遊びます

#Enum.with_index

[
  "abc",
  "def",
  "ghi"
]
|> Enum.with_index()

結果:配列に対して0から順番にインデックスを付けてくれます

[{"abc", 0}, {"def", 1}, {"ghi", 2}]

#Enum.filter

[
 {"abc", 0}, 
 {"def", 1}, 
 {"ghi", 2}
]
|> Enum.filter(&elem(&1, 1) in [0,2])

結果: 数字が0と2で絞り込みしたタプルを取得

[{"abc", 0}, {"ghi", 2}]

#elemの挙動を確認してみよう

elem({"abc", 0}, 0)

結果:タブルの0番目を取得

"abc"
elem({"abc", 0}, 1)

結果:タブルの1番目を取得

0

#Enum.map

[
  {"abc", 0}, 
  {"def", 1}, 
  {"ghi", 2}
 ]
 |> Enum.map(&elem(&1, 0))

結果:タプルの0番目のリストを作成

["abc", "def", "ghi"]

#組み合わせてみよう

[
  "abc",
  "def",
  "ghi"
]
|> Enum.with_index()
|> Enum.filter(&elem(&1, 1) in [0,2])
|> Enum.map(&elem(&1, 0))

結果:0番目と2番目のリストを作成

["abc", "ghi"]

#関数化してみよう

defmodule Hoge do
  def hoge(data, indexes) do
    data
    |> Enum.with_index()
    |> Enum.filter(&elem(&1, 1) in indexes)
    |> Enum.map(&elem(&1, 0))
  end
end


[
  "abc",
  "def",
  "ghi"
]
|> Hoge.hoge([0,2])

結果:0番目と2番目のリストを作成

["abc", "ghi"]
6
2
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
6
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?