Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 21 additions & 7 deletions src/list.jl
Original file line number Diff line number Diff line change
@@ -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}()
Expand All @@ -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)
Expand Down
1 change: 1 addition & 0 deletions test/test_list.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)"
Expand Down