Elixir - Looping through and adding to map

前端 未结 3 1125
再見小時候
再見小時候 2020-12-13 03:55

I\'m rebuilding something in Elixir from some code I built in C#.

It was pretty hacked together, but works perfectly (although not on Linux, hence rebuild).

3条回答
  •  粉色の甜心
    2020-12-13 04:45

    I am also new to Elixir but here is a cute and simple solution that uses pattern matching and recursion.

    defmodule YourModule do
       def reduce_list([], reduced) do reduced end
    
       def reduce_list([first | rest ], reduced) do
          # Do what you need to do here and call the function again 
          # with remaining list items and updated map.
          reduce_list(rest, Map.put(reduced, first, "Done"))
       end
    end 
    

    And call the function with just the list you want to map and an empty map

    > YourModule.reduce_list(["one", "two", "three"], %{})
      %{"one" => "Done", "three" => "Done", "two" => "Done"}
    

提交回复
热议问题