Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Julia produces #undef keys in Dictionary?

I have made a dictionary of histograms on Julia, with a lot of entries. The keys are 4 element integer arrays, as a simple call to the object returns:

In[88] Histogramas
Out[88] Dict{Array{Int64,N},Array{T,N}} with 36540 entries:
  [56,8,39,55]  => [0,2,4,7,19,44,61,76,124,116  …  0,0,0,0,0,0,0,0,0,0]
  [64,20,48,55] => [284,368,202,106,35,3,2,0,0,0  …  0,0,0,0,0,0,0,0,0,0]
  [54,9,50,54]  => [0,0,0,0,0,0,0,0,0,2  …  1,0,0,0,0,0,0,0,0,0]
  [37,26,45,61] => [0,6,11,35,47,86,113,133,136,139  …  0,0,0,0,0,0,0,0,0,0]
  [37,15,51,50] => [673,272,48,5,2,0,0,0,0,0  …  0,0,0,0,0,0,0,0,0,0]
  [35,22,53,45] => [331,370,201,69,25,4,0,0,0,0  …  0,0,0,0,0,0,0,0,0,0]
  [37,25,56,40] => [460,382,127,27,3,0,1,0,0,0  …  0,0,0,0,0,0,0,0,0,0]
....

But if i call Histogramas.keys then I get this very weird output:

Out[90] : 65536-element Array{Array{Int64,N},1}:
 #undef          
 #undef          
    [56,8,39,55] 
 #undef          
    [64,20,48,55]
    [54,9,50,54] 
 #undef          
    [37,26,45,61]
    [37,15,51,50]
...

So I got almost twice keys as there are entries of the dictionary, and most of the extra ones are #undef, which, by the way, I also do not know what that means. ¿Undefined in what sense?

like image 908
wpkzz Avatar asked Feb 06 '23 18:02

wpkzz


1 Answers

That is not the right way to get a Dict's keys – you're accidentally accessing the private internal fields of the Dict object. The correct way to access a Dict's keys is to call the keys function on the Dict object:

julia> d = Dict(:foo => 1.2, :bar => 2.3, :baz => 3.4)
Dict{Symbol,Float64} with 3 entries:
  :bar => 2.3
  :baz => 3.4
  :foo => 1.2

julia> keys(d)
Base.KeyIterator for a Dict{Symbol,Float64} with 3 entries. Keys:
  :bar
  :baz
  :foo

The output #undef when displaying an array indicates an uninitialized entry in the array. This is similar to a null value in C, C++ or Java, but unlike null, in Julia #undef is non-first-class: it is not a value that you can use or pass around; any use of an undefined field or array slot is an immediate exception.

In general, Julia is not a "dot oriented language": whereas in Python or Java you might expect to do obj.frob to access obj's frob or do obj.frizzle() to frizzle obj, in Julia that is unlikely to be the right thing to do. You would most likely do frob(obj) and frizzle(obj) instead.

like image 173
StefanKarpinski Avatar answered Feb 11 '23 00:02

StefanKarpinski