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?
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With