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

Elixir その2Advent Calendar 2020

Day 5

二次元リストの操作(Elixir)

Last updated at Posted at 2020-12-04

この記事は、Elixir その2 Advent Calendar 2020 の5日目です。
前日は とあるサイトでのみ%HTTPoison.Error{id: nil, reason: :closed}が発生 (Elixir) でした。


はじめに

  • Elixirで二次元のリストを操作するにはどうすればいいでしょうか
  • 二次元リストと言っているのはこういうやつのことです
[
  [1, 2, 3],
  [4, 5, 6]
]

結論

たとえばlist_of_lists[1][2]を読み取りたい

Enum.at/2を2回使う

iex> list_of_lists = [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]

iex> Enum.at(list_of_lists, 1) |> Enum.at(2)
6

get_inを使う :star::star::star::star::star:

iex> list_of_lists = [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]

iex> get_in(list_of_lists, [Access.at(1), Access.at(2)]) 
6

- ちなみに三次元はこんな感じ

iex> get_in([[[1, 2, 3], [4, 5, 6]], []], [Access.at(0), Access.at(1), Access.at(2)])
6

たとえばlist_of_lists[1][2]を書き換えたい

EnumモジュールやListモジュールを駆使して書き換える

iex> list_of_lists = [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]

iex> list = Enum.at(list_of_lists, 1) |> List.update_at(2, fn _ -> 8 end)
[4, 5, 8]

iex> List.update_at(list_of_lists, 1, fn _ -> list end)
[[1, 2, 3], [4, 5, 8]]

put_inを使う :star::star::star::star::star:

iex> list_of_lists = [[1, 2, 3], [4, 5, 6]]
[[1, 2, 3], [4, 5, 6]]

iex> put_in(list_of_lists, [Access.at(1), Access.at(2)], 8)
[[1, 2, 3], [4, 5, 8]]

- ちなみに三次元はこんな感じ

iex> put_in([[[1, 2, 3], [4, 5, 6]], []], [Access.at(0), Access.at(1), Access.at(2)], 8)
[[[1, 2, 3], [4, 5, 8]], []]

Wrapping Up :santa::santa_tone1::santa_tone2::santa_tone3::santa_tone4::santa_tone5:

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