From 4dd9022d550eb6dcaf6c98b51c3191d032fcf356 Mon Sep 17 00:00:00 2001 From: arikheinss Date: Sun, 29 Oct 2023 13:36:54 +0100 Subject: [PATCH 1/3] Make LinkedList a Union instead of Abstract type Made Nil and Cons standalone immutable types, with LilnkedList being the Union of the two --- src/list.jl | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/list.jl b/src/list.jl index fbc93b96f..9189b0d99 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}() From 4e2a4378b9c5051bc742e545f0820417f72e15d1 Mon Sep 17 00:00:00 2001 From: arikheinss Date: Sun, 29 Oct 2023 14:07:52 +0100 Subject: [PATCH 2/3] made == for LinkedLists iterative --- src/list.jl | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/src/list.jl b/src/list.jl index 9189b0d99..05f23879a 100644 --- a/src/list.jl +++ b/src/list.jl @@ -20,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) From d2f0813ff05f4b7af9ff07c176a38a02d36f9cd2 Mon Sep 17 00:00:00 2001 From: arikheinss Date: Sun, 29 Oct 2023 14:27:31 +0100 Subject: [PATCH 3/3] added test for LinkedLists of different length Everything for that juicy code coverage --- test/test_list.jl | 1 + 1 file changed, 1 insertion(+) 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)"