From 11613a584983088aa6da1453830fdd05f937c6e8 Mon Sep 17 00:00:00 2001 From: Andrei Borzenkov Date: Wed, 9 Oct 2024 12:53:18 +0400 Subject: [PATCH] Use direct recursion in folding functions --- src/PersistentOrderedMap.mo | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/src/PersistentOrderedMap.mo b/src/PersistentOrderedMap.mo index ecf51626..f93e4a61 100644 --- a/src/PersistentOrderedMap.mo +++ b/src/PersistentOrderedMap.mo @@ -536,11 +536,14 @@ module { combine : (Key, Value, Accum) -> Accum ) : Accum { - var acc = base; - for(val in iter(rbMap, #fwd)){ - acc := combine(val.0, val.1, acc); - }; - acc + switch (rbMap) { + case (#leaf) { base }; + case (#node(_, l, (k, v), r)) { + let left = foldLeft(l, base, combine); + let middle = combine(k, v, left); + foldLeft(r, middle, combine) + } + } }; /// Collapses the elements in `rbMap` into a single value by starting with `base` @@ -576,11 +579,14 @@ module { combine : (Key, Value, Accum) -> Accum ) : Accum { - var acc = base; - for(val in iter(rbMap, #bwd)){ - acc := combine(val.0, val.1, acc); - }; - acc + switch (rbMap) { + case (#leaf) { base }; + case (#node(_, l, (k, v), r)) { + let right = foldRight(r, base, combine); + let middle = combine(k, v, right); + foldRight(l, middle, combine) + } + } };