Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Convert List into a Map

Tags:

elixir

What would be an elegant, efficient way for converting a list like [1,2,3,4] into the map %{1=>2, 3=>4}? I wrote this:

     Enum.reduce([1,2,3,4],%{}, fn(item, acc) ->
        case Map.get(acc, :last) do
          nil ->
            Map.put(acc, :last, item)
          last ->
            acc = Map.put(acc, item, last)
            Map.drop(acc, [:last])
        end
      end)

But this does not seem very elegant. Is there a more elegant and cleaner way of doing this?

like image 400
Chip Dean Avatar asked Feb 15 '17 23:02

Chip Dean


2 Answers

You can avoid the extra call to Enum.map/2, and build the new map directly using Map.new/2:

[1,2,3,4]
|> Enum.chunk_every(2)
|> Map.new(fn [k, v] -> {k, v} end)

Update: The previous version of this answer used chunk/2 but that has been deprecated in favor of chunk_every/2.

like image 106
Sheharyar Avatar answered Oct 24 '22 16:10

Sheharyar


You can use Enum.chunk_every/2:

[1, 2, 3, 4] 
  |> Enum.chunk_every(2) 
  |> Enum.map(fn [a, b] -> {a, b} end) 
  |> Map.new
like image 27
nietaki Avatar answered Oct 24 '22 17:10

nietaki