如何使用特定的键值对替换MapSet的Map中的值?

时间:2017-08-31 17:33:50

标签: elixir

我是函数式编程的新手,所以我稍微努力了。

我试图通过Map中的Key在MapSet中找到Map,然后替换另一个值。我的方法是,在MapSet中找到Map,然后从MapSet中删除Map,替换Map中的值并将其重新添加。

def replace_in_mapset_by_id(mapset, id, key, value) do
    # Find the Map that matches the ID of the Map we are looking for
    foundMap = (Enum.find(mapset, fn(x) -> Map.get(x, "ID") == id end))

    # Remove the found Map from the MapSet
    remove(mapset, foundMap)

    # Replace the Key Value that we are trying update
    updatedMap = Map.replace(foundMap, key, value)
    add(mapset, updatedMap)
end

1 个答案:

答案 0 :(得分:3)

另一种[我相信更惯用]的方法是使用带变压器MapSet.new/2的工厂:

iex|1 ▶ map = MapSet.new([%{id: 1, key: :foo}, %{id: 2, key: :bar}])
#MapSet<[%{id: 1, key: :foo}, %{id: 2, key: :bar}]>

iex|2 ▶ MapSet.new(map, fn                 
...|2 ▶   %{id: 1} = old -> %{old | key: :baz}
...|2 ▶   any -> any
...|2 ▶ end)
#MapSet<[%{id: 1, key: :baz}, %{id: 2, key: :bar}]>

在你的功能中使用:

def replace_in_mapset_by_id(mapset, id, key, value) do
  MapSet.new(mapset, fn                 
    %{id: ^id} = old -> %{old | key => value} # update only
    # %{id: ^id} = old -> Map.put(old, key, value) # update/insert
    any -> any
  end)
end