Skip to content

perf: improve @list.from_iter use one pass #2036

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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
17 changes: 16 additions & 1 deletion list/list.mbt
Original file line number Diff line number Diff line change
Expand Up @@ -1199,7 +1199,22 @@ pub fn[A] iter2(self : T[A]) -> Iter2[Int, A] {
/// Convert the iterator into a list. Preserves order of elements.
/// If the order of elements is not important, use `from_iter_rev` instead.
pub fn[A] from_iter(iter : Iter[A]) -> T[A] {
iter.fold(init=Empty, fn(acc, e) { More(e, tail=acc) }).reverse_inplace()
let mut res = Empty
let mut ptr = Empty
for x in iter {
match (res, ptr) {
(Empty, _) => {
res = More(x, tail=Empty)
ptr = res
}
(More(_), More(_) as ptr_) => {
ptr_.tail = More(x, tail=Empty)
ptr = ptr_.tail
}
(_, _) => abort("unreachable")
}
}
res
}

///|
Expand Down
Loading