Optimize `vlist-fold-right'.
authorLudovic Courtès <ludo@gnu.org>
Sun, 8 May 2011 16:15:10 +0000 (18:15 +0200)
committerLudovic Courtès <ludo@gnu.org>
Sun, 8 May 2011 16:20:42 +0000 (18:20 +0200)
* module/ice-9/vlist.scm (vlist-fold-right): Avoid `vlist-reverse' and
  instead `vlist-ref' individual elements.  The result is about twice
  faster.  Thanks Andy for suggesting it indirectly.  :-)

module/ice-9/vlist.scm

index 34c7c00..b554e11 100644 (file)
@@ -245,7 +245,14 @@ tail."
 (define (vlist-fold-right proc init vlist)
   "Fold over @var{vlist}, calling @var{proc} for each element, starting from
 the last element."
-  (vlist-fold proc init (vlist-reverse vlist)))
+  (define len (vlist-length vlist))
+
+  (let loop ((index  (1- len))
+             (result init))
+    (if (< index 0)
+        result
+        (loop (1- index)
+              (proc (vlist-ref vlist index) result)))))
 
 (define (vlist-reverse vlist)
   "Return a new @var{vlist} whose content are those of @var{vlist} in reverse