gpt4 book ai didi

Elixir - 如何深度合并 map ?

转载 作者:行者123 更新时间:2023-12-04 01:19:17 25 4
gpt4 key购买 nike

Map.merge我有:

Map.merge(%{ a: %{ b: 1 }}, %{ a: %{ c: 3 }}) # => %{ a: %{ c: 3 }}

但实际上我想:
Map.merge(%{ a: %{ b: 1 }}, %{ a: %{ c: 3 }}) # => %{ a: %{ b: 1, c: 3 }}

在这种情况下,是否有没有编写递归样板函数的本地方法?

最佳答案

正如@Dogbert 建议的那样,您可以编写一个函数来递归合并 map 。

defmodule MapUtils do
def deep_merge(left, right) do
Map.merge(left, right, &deep_resolve/3)
end

# Key exists in both maps, and both values are maps as well.
# These can be merged recursively.
defp deep_resolve(_key, left = %{}, right = %{}) do
deep_merge(left, right)
end

# Key exists in both maps, but at least one of the values is
# NOT a map. We fall back to standard merge behavior, preferring
# the value on the right.
defp deep_resolve(_key, _left, right) do
right
end
end

以下是一些测试用例,可让您了解如何解决冲突:
ExUnit.start

defmodule MapUtils.Test do
use ExUnit.Case

test 'one level of maps without conflict' do
result = MapUtils.deep_merge(%{a: 1}, %{b: 2})
assert result == %{a: 1, b: 2}
end

test 'two levels of maps without conflict' do
result = MapUtils.deep_merge(%{a: %{b: 1}}, %{a: %{c: 3}})
assert result == %{a: %{b: 1, c: 3}}
end

test 'three levels of maps without conflict' do
result = MapUtils.deep_merge(%{a: %{b: %{c: 1}}}, %{a: %{b: %{d: 2}}})
assert result == %{a: %{b: %{c: 1, d: 2}}}
end

test 'non-map value in left' do
result = MapUtils.deep_merge(%{a: 1}, %{a: %{b: 2}})
assert result == %{a: %{b: 2}}
end

test 'non-map value in right' do
result = MapUtils.deep_merge(%{a: %{b: 1}}, %{a: 2})
assert result == %{a: 2}
end

test 'non-map value in both' do
result = MapUtils.deep_merge(%{a: 1}, %{a: 2})
assert result == %{a: 2}
end
end

关于Elixir - 如何深度合并 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38864001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com