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

はじめに

Advent Of Code等を解いていると行列を転置したいことがあります。

たとえばインプットが以下だとしてします。

list_of_lists = [[1, 2, 3],
                 [4, 5, 6],
                 [7, 8, 9]]

期待結果は次の通りです。

[
 [1, 4, 7],
 [2, 5, 8],
 [3, 6, 9]
]

果たしてどうやるとよいでしょうか。

Enum.zip_with !!!

Enum.zip_with(list_of_lists, & &1)

これがオススメです。Kiro CLIに教えてもらいました。

力ワザ

height = Enum.count(list_of_lists)
width = Enum.at(list_of_lists, 0) |> Enum.count()

(for i <- 0..(height - 1), j <- (0..(width - 1)), do: {j, i})
|> Enum.map(fn {row, col} -> Enum.at(list_of_lists, row) |> Enum.at(col) end)
|> Enum.chunk_every(height)

これでも一応できますが、Enum.zip_with/2を使ったほうがよっぽど簡単にできます。力ワザでは、Elixirでプログラミングしているっぽい感じがあまりしません…… なにやら手続き型言語で書いているみたいな雰囲気になってしまいます。
この記事で紹介するEnum.zip_with(enumerables, & &1)は、いかにも関数型プログラミング言語をよく使いこなしている感じがして美しいです。

さいごに

イディオムとして覚えたいElixirでの転置 Enum.zip_with(enumerables, & &1)のご紹介でした。

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