Warm tip: This article is reproduced from stackoverflow.com, please click
dictionary elixir

Elixir make a self reference in a map

发布于 2020-03-27 10:22:53

I have this map

%{
  total: 38,
  value: 22
}

And would like to add the key :ratio. Is there a way to write immediately:

%{
  total: 38,
  value: 22,
  ratio: __SELF__.value / __SELF__.total
}

or do I need to create another map to achieve this?

Thanks

Questioner
Augustin Riedinger
Viewed
46
Adam Millerchip 2019-07-03 22:33

All data is immutable, so you always have to make a new map.

A simple way, assuming your map is called map:

iex> Map.put(map, :ratio, map.value / map.total)
%{ratio: 0.5789473684210527, total: 38, value: 22}

If you mean that you want to create the map before it already exists, then it would be better to put total and value into variables, and use them to build the map:

defmodule Example do
  def make_map(total, value) do
    %{total: total, value: value, ratio: value / total}
  end
end

iex(1)> Example.make_map(38, 22)
%{ratio: 0.5789473684210527, total: 38, value: 22}