Julia: add an element to an array of custom types

Adding an element to an array in Julia works as follows:

v = Array{Int32, 1}(0) append!(v, 1) append!(v, 2) println(v) # prints: Int32[1,2] 

When I try this with a custom type

 type Node label::String value::Int32 end nodes = Array{Node, 1}(0) append!(nodes, Node("a", 42)) 

I get the following error:

 ERROR: LoadError: MethodError: no method matching length(::Node) 

I assume that I need to "implement" the length method, but I donโ€™t know how to do it.

+5
source share
2 answers

append! team Don't do what you think. Are you thinking of the push! team push! .

append! team combines two arrays. Both arguments must be arrays:

 julia> append!(nodes, [Node("a", 42)]) 1-element Array{Node,1}: Node("a",42) 

No length execution needed (this error just told you that it was trying to read the length of your array for the second argument and found that it was not an array.)

+8
source

try it

 Base.append!(x::Array{Node,1}, val::Node) = push!(x, val) 

then you get

 append!(nodes, Node("a", 42)) 1-element Array{Node,1}: Node("a",42) 

you need to explicitly create a function for this particular type, since append! or any of the Base functions sometimes (or maybe I always checked havent) don't accept Any

+1
source

Source: https://habr.com/ru/post/1259896/


All Articles