diff --git a/src/list.jl b/src/list.jl index fbc93b96f..05f23879a 100644 --- a/src/list.jl +++ b/src/list.jl @@ -1,15 +1,16 @@ -abstract type LinkedList{T} end -Base.eltype(::Type{<:LinkedList{T}}) where T = T -mutable struct Nil{T} <: LinkedList{T} -end +struct Nil{T} end -mutable struct Cons{T} <: LinkedList{T} +struct Cons{T} head::T - tail::LinkedList{T} + tail::Union{Nil{T}, Cons{T}} end +const LinkedList{T} = Union{Nil{T}, Cons{T}} + +Base.eltype(::Type{<:LinkedList{T}}) where T = T + cons(h, t::LinkedList{T}) where {T} = Cons{T}(h, t) nil(T) = Nil{T}() @@ -19,7 +20,20 @@ head(x::Cons) = x.head tail(x::Cons) = x.tail Base.:(==)(x::Nil, y::Nil) = true -Base.:(==)(x::Cons, y::Cons) = (x.head == y.head) && (x.tail == y.tail) +function Base.:(==)(x::LinkedList, y::LinkedList) + # can be changed to the more elegant + # Base.:(==)(x::Cons, y::Cons) = (x.head == y.head) && (x.tail == y.tail) + # once julia supports tail call recursions + while x isa Cons && y isa Cons + x.head == y.head || return false + x = x.tail + y = y.tail + end + if x isa Cons || y isa Cons + return false + end + return true +end function Base.show(io::IO, l::LinkedList{T}) where T if isa(l,Nil) diff --git a/test/test_list.jl b/test/test_list.jl index 389d481e5..f6cbcb4a2 100644 --- a/test/test_list.jl +++ b/test/test_list.jl @@ -56,6 +56,7 @@ l4 = cat(l1, l2, l3) @test length(l4) == 3 @test l4 == list(1, 2, 3) + @test l4 ≠ list(1, 2) @test collect(l4) == [1; 2; 3] @test collect(copy(l4)) == [1; 2; 3] @test sprint(show,l4) == "list(1, 2, 3)"