Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MethodError calling constructor of parametric struct

Tags:

struct

julia

I'm trying to create a linked list in Julia. I have:

mutable struct LLNode{T}
    x::T
    next::Union{LLNode{T},Void}
    prev::Union{LLNode{T},Void}
end

mutable struct LinkedList{T}
   count::Int
   head::Union{LLNode{T},Void}
   tail::Union{LLNode{T},Void}
end

Now, the above code compiles fine. I can also run:x = LLNode(0,nothing,nothing) fine. But when I run y = LinkedList(0,nothing,nothing) I get a no method matching LinkedList(::Int64, ::Void, ::Void) error. What gives?

VERSION returns v"0.6.2"

like image 330
David Varela Avatar asked Feb 13 '26 01:02

David Varela


1 Answers

When you write LLNode(0,nothing,nothing), Julia is able to figure out that it needs to construct an LLNode{Int} based upon the type of the first argument. But in LinkedList(0, nothing, nothing), there's quite literally nothing for it to go on to determine what the type parameter should be, so it doesn't know what to construct.

Instead, you either need to explicitly choose what you want T to be:

julia> LinkedList{Int}(0, nothing, nothing)
LinkedList{Int64}(0, nothing, nothing)

or it can get the T based upon a not-nothing argument:

julia> LinkedList(0, LLNode(0, nothing, nothing), nothing)
LinkedList{Int64}(0, LLNode{Int64}(0, nothing, nothing), nothing)
like image 54
mbauman Avatar answered Feb 15 '26 14:02

mbauman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!