Julia: Append an element to an array of custom typ

2019-02-24 09:16发布

Appending an element to an array in Julia works like this:

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 I have to 'implement' the length method but do not know how.

标签: arrays julia
2条回答
再贱就再见
2楼-- · 2019-02-24 10:01

Try this

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've got to explicitly create a function for this particular type as append! or any of the Base functions sometimes (or perhaps always I havent checked) wont accept Any

查看更多
劳资没心,怎么记你
3楼-- · 2019-02-24 10:08

The append! command doesn't do what you think it does. You're thinking of the push! command.

The append! command appends two arrays together. Both arguments need to be arrays:

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

No length implementing necessary
(that error was just telling you it tried to read the length of your array for the second argument and found something that was not an array.)

查看更多
登录 后发表回答