Using mutable structs in this version.
abstract type ChainedList{T} end
struct EmptyList{T} <: ChainedList{T}
end # "singleton" : no data at all
mutable struct NonEmptyList{T} <: ChainedList{T}
first::T
rest::ChainedList{T}
end
We define -->
so that a --> L
adds a
(of type T
) in the front of L
, and a --> b
creates a list with two elements. So a --> b --> c
creates a list with three elements, and so on.
function -->(a::T, L::ChainedList{T}) where {T}
return NonEmptyList{T}(a, L)
end
function -->(a::T, b::T) where {T}
empty= EmptyList{T}()
return NonEmptyList{T}(a, NonEmptyList(b, empty))
end
function inner_string(L::EmptyList)
return ""
end
function inner_string(L::NonEmptyList{T}) where {T}
if L.rest == EmptyList{T}()
return string(L.first)
else
return string(L.first) * " --> " * inner_string(L.rest)
end
end
function Base.string(L::ChainedList)
return "(" * inner_string(L) * ")"
end
function Base.print(L::ChainedList)
print(string(L))
end
# the following does not work :
function Base.show(io,mime::MIME"text/plain",L::ChainedList{T}) where {T}
println(io, string(L))
end
Without any copying!
function extend!(L1::NonEmptyList{T}, L2::ChainedList{T}) where {T}
if L1.rest == EmptyList{T}()
L1.rest= L2
else
extend!(L1.rest, L2)
end
end
L= 5 --> 4 --> 3 --> 2 --> 1;
print(L)
L2= 5 --> 4 --> 3 --> 2 --> 1;
print(L2)
L == L2
extend!(L, L2) # no output since the new Base.show does not work
print(L)