Lars Brinkhoff wrote:
> > use LOOP to collect random integers into a list until the sum of that
> > list exceeds a constant (say 50).
>
> (loop for x = (random 10) collect x sum x into y until (> y 50))
(g.mfold-until (list + xcons) (@ > ! 50) '(0 ()) (gen-rand 10))
===>
'(53 (7 7 4 9 0 9 6 0 8 3))
Given:
(define (xcons a b) (cons b a))
(define (gen-rand n) (lambda () (random n)))
(define-syntax @
(syntax-rules (! !! !!!)
[(@ () (x ...) args) (lambda args (x ...))]
[(@ (! a ...) (x ...) args) (@ (a ...) (x ... (car args)) args)]
[(@ (!! a ...) (x ...) args) (@ (a ...) (x ... (cadr args)) args)]
[(@ (!!! a ...) (x ...) args)
(@ (a ...) (x ... (caddr args)) args)]
[(@ (a b ...) (x ...) args) (@ (b ...) (x ... a) args)]
[(@ x ...) (@ (x ...) () args)]))
;; Sources can be lists or generators.
;; Order of arguments to func is different from SRFI-1.
;; predicate is tested on the result of applying func to the object.
(define (g.fold-until func predicate seed source0 . sources)
(if (null? sources)
(if (procedure? source0)
(let loop ((seed seed))
(let ((x (source0)))
(if (eof-object? x)
seed
(let ((new-seed (func seed x)))
(if (predicate new-seed)
new-seed
(loop new-seed))))))
(let loop ((seed seed) (xs source0))
(if (null? xs)
seed
(let ((new-seed (func seed (car xs))))
(if (predicate new-seed)
new-seed
(loop new-seed (cdr xs)))))))
(let ((sources (cons source0 sources)))
(if (g.member-f procedure? sources)
(let ((sources
(map (lambda (x) (if (procedure? x) x (gen-list x))) sources)))
(let loop ((seed seed))
(let ((xs (map (lambda (g) (g)) sources)))
(if (g.member-f eof-object? xs)
seed
(let ((new-seed (apply func (cons seed xs))))
(if (predicate new-seed)
new-seed
(loop new-seed)))))))
(let loop ((seed seed) (lists sources))
(if (g.member-f null? lists)
seed
(let ((new-seed (apply func (cons seed (map car lists)))))
(if (predicate new-seed)
new-seed
(loop new-seed (map cdr lists))))))))))
(define (g.mfold-until funcs predicate seed . sources)
(apply g.fold-until
(lambda (accum . xs)
(map (lambda (fn old-val)
(apply fn old-val xs))
funcs
accum))
(lambda (xs) (apply predicate xs))
seed
sources))
--
The report card by the American Society of Civil Engineers showed the national
infrastructure a single grade above failure, a step from declining to the point
where everyday things simply stop working the way people expect them to.
http://archive.org/details/nolies