chickadee » sicp » ambeval-fold

ambeval-fold exp env cons nilprocedure
ambeval-fold exp env cons nil nprocedure

Folds over the results of up to n successful executions of exp; if n is missing, folds over all successful executions until failure.

exp
The expression to execute
env
The environment to execute it in
cons
The aggregator
nil
The initial value
n
The number of results to gather
(define ambeval-fold
  (case-lambda
    ((exp env cons nil) (ambeval-fold exp env cons nil +inf.0))
    ((exp env cons nil n)
     (let ((result nil))
       (ambeval
         exp
         env
         (lambda (val next-alternative)
           (set! n (- n 1))
           (if (negative? n)
             result
             (begin (set! result (cons val result)) (next-alternative))))
         (lambda () result))))))