LoginSignup
10
1

【TIPS】案外知られていないEnum.into

Last updated at Posted at 2023-12-18

この記事は、Elixir Advent Calendar 2023 シリーズ11 の19日目です


【本コラムは、5分で読め、2分で試せます】

piacere です、ご覧いただいてありがとございます :bow:

Enum.into って、けっこう便利に使えるのですが、案外、知られていない関数の1つなんじゃ無いかなって思います

それをTIPSとしてまとめておきました

使い方

キーワードリストをマップに1発変換できます

[a: 123, b: 456]
|> Enum.into(%{})
結果
%{a: 123, b: 456}

逆も然りです

%{a: 123, b: 456}
|> Enum.into([])
結果
[a: 123, b: 456]

つまり、第二引数に指定した型で、第一引数(パイプの前)のデータを変換するということです

正確に言うと、Enumerable のデータを Collectable に変換するのが、Enum.into です

そのため、タプルや文字列、バイナリのような Collectable に属さないデータには変換不可です

[123, 456]
|> Enum.into({})
結果
** (Protocol.UndefinedError) protocol Collectable not implemented for {} of type Tuple. This protocol is implemented for the following type(s): BitString, File.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Mix.Shell
    (elixir 1.15.7) lib/collectable.ex:1: Collectable.impl_for!/1
    (elixir 1.15.7) lib/collectable.ex:92: Collectable.into/1
    (elixir 1.15.7) lib/enum.ex:1534: Enum.into_protocol/2
    #cell:2ugmh3yq3flnvles:2: (file)

ひとまず、キーワードリストとマップのようなKeyValueに特化した関数だと思っていればOKです

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