Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve LinkedList Base.map performance by not having to reverse the list #763

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
18 changes: 14 additions & 4 deletions src/list.jl
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,22 @@ end
Base.map(f::Base.Callable, l::Nil) = l

function Base.map(f::Base.Callable, l::Cons{T}) where T
first = f(l.head)
# Tail recursion manually unrolled into iterative loop with local stack to avoid
# StackOverflow exception. The recursive logic is:
# map(f::Base.Callable, l::Cons) = cons(f(head(l)), map(f, tail(l)))
# Recursion to iteration instructions: https://stackoverflow.com/a/159777/751061
stack = Vector{T}()
while !(tail(l) isa Nil)
push!(stack, head(l))
l::Cons{T} = tail(l)::Cons{T}
end
# Note the new list might have a different eltype than T
first = f(head(l))
l2 = cons(first, nil(typeof(first) <: T ? T : typeof(first)))
for h in l.tail
l2 = cons(f(h), l2)
for i in reverse(1:length(stack))
l2 = cons(f(stack[i]), l2)
end
reverse(l2)
return l2
end

function Base.filter(f::Function, l::LinkedList{T}) where T
Expand Down