Skip to content

Commit c36e392

Browse files
illusory0x0bobzhang
authored andcommitted
perf: use array as buffer
1 parent 9b021cf commit c36e392

File tree

2 files changed

+9
-8
lines changed

2 files changed

+9
-8
lines changed

immut/list/list.mbt

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -364,14 +364,10 @@ pub fn fold[A, B](self : T[A], init~ : B, f : (B, A) -> B) -> B {
364364
/// assert_eq!(r, 15)
365365
/// ```
366366
pub fn rev_fold[A, B](self : T[A], init~ : B, f : (A, B) -> B) -> B {
367-
let tsil = self.rev() // avoid stack overflow, because we don't know `f` will use how much stack.
367+
let xs = self.to_array()
368368
let mut acc = init
369-
loop tsil {
370-
Nil => ()
371-
Cons(x, xs) => {
372-
acc = f(x, acc)
373-
continue xs
374-
}
369+
for x in xs.rev_iter() {
370+
acc = f(x, acc)
375371
}
376372
acc
377373
}

list/list.mbt

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -423,7 +423,12 @@ pub fn fold[A, B](self : T[A], init~ : B, f : (B, A) -> B) -> B {
423423
/// assert_eq!(r, 15)
424424
/// ```
425425
pub fn rev_fold[A, B](self : T[A], init~ : B, f : (B, A) -> B) -> B {
426-
self.rev().fold(init~, f)
426+
let xs = self.to_array()
427+
let mut acc = init
428+
for x in xs.rev_iter() {
429+
acc = f(acc, x)
430+
}
431+
acc
427432
}
428433
429434
///|

0 commit comments

Comments
 (0)