Skip to content

Commit 16a2c20

Browse files
committed
feat(iter): implement last method for Iter to return the last element or None
1 parent aebfe53 commit 16a2c20

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

builtin/iter.mbt

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ pub fn[T] Iter::eachi(self : Iter[T], f : (Int, T) -> Unit) -> Unit {
108108
///
109109
/// Returns the final accumulator value after folding all elements of the iterator.
110110
#intrinsic("%iter.reduce")
111+
#locals(f)
111112
pub fn[T, B] Iter::fold(self : Iter[T], init~ : B, f : (B, T) -> B) -> B {
112113
let mut acc = init
113114
for a in self {
@@ -849,11 +850,11 @@ pub fn[T] Iter::iter(self : Iter[T]) -> Iter[T] {
849850
///|
850851
/// Returns the last element of the iterator, or `None` if the iterator is empty.
851852
pub fn[A] Iter::last(self : Iter[A]) -> A? {
852-
fn f(_a : A?, b : A) {
853-
Some(b)
853+
let mut last = None
854+
for a in self {
855+
last = Some(a)
854856
}
855-
856-
self.fold(init=None, f)
857+
last
857858
}
858859
859860
///|

0 commit comments

Comments
 (0)