Sujet : Re: simple loop question
De : Nobody447095 (at) *nospam* here-nor-there.org (B. Pym)
Groupes : comp.lang.lispDate : 28. Jun 2025, 20:11:11
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <103peoc$11fde$1@dont-email.me>
References : 1
User-Agent : XanaNews/1.18.1.6
B. Pym wrote:
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))
Gauche Scheme
If we are allowed to set up a couple of collectors, the
solution is tiny. Comparing it to the LOOP version:
(until (> (s (c (random 10))) 50)) (c)
(loop for x = (random 10) collect x sum x into y until (> y 50))
Here's the code:
(use srfi-27) ;; random-integer
(define random random-integer)
(let ((c (mlistbag)) (s (mbag 0 +)))
(until (> (s (c (random 10))) 50))
(c))
===>
(8 1 9 8 1 9 9 2 6)
Given:
(define (mbag init func :optional (pass-through #f))
(let ((val init) (func func) (pass-through pass-through))
(lambda args
(if (null? args)
val
(begin
(set! val
;; A "kons" may have been supplied.
((if (null? (cdr args)) func (cadr args))
(car args) val))
(if pass-through
(car args)
val))))))
(define (mlistbag :optional (pass-through #t))
(let ((bag (mbag '() cons pass-through)))
(lambda args
(if (null? args)
(reverse (bag))
(apply bag args)))))