0

In my module I have a function whose purpose is to generate a Map with some defaults, given immutability in Elixir I couldn't find a proper way of achieving this:

defmodule Teams do

  def past_matches() do
    [
      team1: %{team2: %{f: 0, a: 1},  team3: %{f: 1, a: 3}},
      team2: %{team1: %{f: 3, a: 0},  team3: %{f: 2, a: 0}},
    ]
  end

  def initialize(matches, table) do
    Enum.each matches, fn {team, _scores} ->
      Map.put local, team, %{total: 0}
    end
  end

  def run() do
    table = %{}

    past_matches()
    |> initialize(table)
  end

end

The idea on initialize() is to populate the Map table with: %{team1: %{total: 0}, team2: %{total: 0}, team3: %{total: 0}}

I understand that the variable table is still an empty Map after the piped functions are done but what is the Elixir way of dynamically creating temporary structures like this ?

Relevant: Elixir - Looping through and adding to map, but I think this is ugly by design and not perfectly suited for maps as the iterable.

PepperoniPizza
  • 8,842
  • 9
  • 58
  • 100
  • 1
    The solution in that answer, i.e. using `Enum.reduce` would be the cleanest way I can think of. Did you try using it? Can you post the code you tried that turned out to be ugly? – Dogbert Jun 04 '17 at 16:48
  • 2
    `Enum.reduce matches, local, fn {team, _scores}, acc -> Map.put acc, team, %{total: 0} end`. – Dogbert Jun 04 '17 at 16:49
  • There seems to be a lot of these questions on SO. Basic of immutability is you can't mutate things, which is essentially what you're trying to do with table here. – Owen Jun 08 '17 at 17:42

0 Answers0