Created
January 4, 2023 01:17
-
-
Save thautwarm/330995f5aeefd297fe23ea10cb0dc74d to your computer and use it in GitHub Desktop.
Non-empty & persistent linked lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct NZList{T} | |
head::T | |
tail::Union{NZList{T},Nothing} | |
end | |
cons(x) = NZList(x, nothing) | |
cons(x::T, xs::Union{NZList{T},Nothing}) where {T} = NZList(x, xs) | |
function Base.iterate(xs::NZList) | |
xs.head, xs.tail | |
end | |
function Base.iterate(xs::NZList, state::Union{Nothing, NZList}) | |
if isnothing(state) | |
nothing | |
else | |
state.head, state.tail | |
end | |
end | |
function Base.collect(xs::NZList{T}) where T | |
let xs::Union{NZList{T},Nothing} = xs | |
out = T[] | |
while !isnothing(xs) | |
push!(out, xs.head) | |
xs = xs.tail | |
end | |
out | |
end | |
end | |
function Base.show(io::IO, xs::NZList) | |
show(io, collect(xs)) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment