我是朱莉娅的新手。对于我的应用程序,我有一个昂贵的操作来基于两个点来计算矩阵。计算的矩阵将被多次使用,因此尽管我会将它们缓存在字典中。但是,我在Julia中遇到了奇怪的行为。如果我添加第一对(键,值)作为字典初始化的一部分,那么一切都会按预期进行。但是,如果我不这样做,然后尝试添加我的第一对(键,值),朱莉娅就会炸弹爆炸。
p1 = [ 2.0, 1.0, 1.0]
p2 = [ 4.0, 2.0, 1.0]
# This works
my_dict = Dict{Tuple{Array{Float64,1}, Array{Float64,1}}, String}(
(p1, p2) => "hello world"
)
println(my_dict[(p1, p2)])
# This works
my_dict[ (p2, p1)] = "hello again"
println(my_dict[ (p2, p1)] )
# This doesn't
my_dict2 = Dict{Tuple{Array{Float64,1}, Array{Float64,1}}, String}
my_dict2[(p2, p1)] = "this fails with method dispatch error"
朱莉娅的输出:
julia complex_key_for_dict.jl
hello world
hello again
ERROR: LoadError: MethodError: no method matching setindex!(::Type{Dict{Tuple{Array{Float64,1},Array{Float64,1}},String}}, ::String, ::Tuple{Array{Float64,1},Array{Float64,1}})
Stacktrace:
[1] top-level scope at none:0
[2] include at ./boot.jl:326 [inlined]
[3] include_relative(::Module, ::String) at ./loading.jl:1038
[4] include(::Module, ::String) at ./sysimg.jl:29
[5] exec_options(::Base.JLOptions) at ./client.jl:267
[6] _start() at ./client.jl:436
in expression starting at /home/peter/julia/gps_analysis/complex_key_for_dict.jl:16
现在,我将仅在虚拟字典中添加一个虚构的第一项,但是如果有人可以直截了当地指出我的错误,将不胜感激。
答案 0 :(得分:1)
没有什么比向我发布问题到StackOverflow更好的了。这有效:
# This works. Added an open/close bracket to the end of the Dict defintion
my_dict2 = Dict{Tuple{Array{Float64,1}, Array{Float64,1}}, String}()
my_dict2[ (p2, p1)] = "this now works"
println(my_dict2[ (p2, p1)])
我认为应该发布答案,以便其他任何人也可以将其撞到砖墙上。