我想在 Julia 中编写一个合并两个字典的函数。
function merge(left::Dict, right::Dict)::Dict
语义如下:
- 输入
left
为right
left
和都right
拥有其数据的所有权,这意味着它们将在函数调用后被修改,并且不应对它们包含的数据做出任何保证- 返回值包含两个字典的数据
- 如果任何键同时存在于两者中
left
,并且right
值left
保持不变
以下是关于如何解决此问题的一些初步想法。(这是带有注释的伪代码,而不是可以实际编译的代码。)
function mergeDict(left::Dict, right::Dict)::Dict
# create a new dictionary from `left`
return_value = left
# move data from `right` to `left`, "no-clobber"
for k, v in pop_next!(right)
# the function `pop_next!` does not exist, no iterator-like `pop!`
for k in keys(right)
v = pop!(right, k)
# does this work as expected? destructive operation while reading keys?
# `keys()` returns an *iterator*, not a collection! (?)
if !haskey(left, k)
push!(left, k, v) # no `push!` function
left[k] = v # this works instead
end
end
# `left` and `right` are not pointers, but "copy-by-value references"
# just as in Python, so this doesn't work
left = nothing
right = nothing
# we want to invalidate the data, how to do that?
# this also won't work because `left` references the same data
# structure as `return_value`
clear(left)
clear(right)
end
您可以看到,我尝试编写手动实现。我确信 Julia 会有一些有用的函数作为标准库的一部分来实现这一点,但是由于我是 Julia 新手,我不知道这些函数是什么。
我找到了函数merge
、和mergewith
,然而这些函数似乎都不具备上面描述的语义。merge!
mergewith!