Using iterator in Julia 0.7

I’m trying to implement the iterator interface on a toy linked list implementation. I believe I’m getting it right, but I keep getting an error I don’t know how to handle. I’m using this reference. I tried unsuccessfully to find examples, so I’m at a dead end for now.

The error is: no method matching iterate(::LinkedList{Int64})

My code:

mutable struct LLNode{T}
    data::T
    next::Union{LLNode{T},Nothing}
    prev::Union{LLNode{T},Nothing}
end
LLNode(d::T) where {T} = LLNode{T}(d,nothing,nothing)

mutable struct LinkedList{T}
    count::Int
    head::Union{LLNode{T},Nothing}
    tail::Union{LLNode{T},Nothing}
    #LinkedList{T}() where {T} = LinkedList(0,nothing,nothing)
end

is_empty(ll::LinkedList) = (ll.count == 0)
is_singular(ll::LinkedList) = (ll.count == 1)

function ll_push!(ll::LinkedList{T}, val::T) where {T}
    x::LLNode{T} = LLNode(val)
    if is_empty(ll)
        ll.head = ll.tail = x
    else
        x.prev = ll.tail
        ll.tail = ll.tail.next = x
    end

    ll.count += 1
end

function iterate(ll::LinkedList{T}) where {T}
    if ll.head === nothing
        return nothing
    end
    return (ll.head.data, ll.head)
end

function iterate(ll::LinkedList{T}, x::LLNode{T}) where {T}
    if x.next === nothing
        return nothing
    end
    return (x.next.data, x.next)
end

function print_list(ll::LinkedList{T}) where {T}
    for x in ll
        println(x.data)
    end
end

ll = LinkedList{Int}(0,nothing,nothing)
ll_push!(ll,1)
ll_push!(ll,2)
ll_push!(ll,3)
print_list(ll)

Are you importing iterate for method extension with an import Base: iterate? Or, alternatively, just use function Base.iterate(…) … at the definition site.

1 Like

Yes, that was my issue. Thank you for pointing that out