[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.lisp

Re: The LOOP macro

William James

8/8/2015 12:42:00 AM

Peter Seibel wrote:

> > Do you have a good example of LOOP's power / flexibility that doesn't
> > need much surrounding context to understand?
>
> Here are a few:
>
> (loop repeat 100 collect (random 10))


Gauche Scheme:

(use srfi-1 :only (list-tabulate))
(use srfi-27 :only (random-integer))

(list-tabulate 100 (^x (random-integer 10)))


>
> (loop for x across array-of-numbers
> minimizing x into min
> maximizing x into max
> summing x into total
> counting t into count
> finally (return (list min max (/ total count))))

Barry Margolin (1997-01-08):

There are a few things that can be done extremely conveniently
with LOOP, and I will usually use LOOP in those cases. In
particular, the COLLECTING feature is one of the most
convenient.

The Generators and Collectors macros described in Appendix B
of CLtL2 also provide this convenience and are much more
Lisp-like. It's too bad they weren't around when LOOP was
gaining popularity, and I think they're a better way to go.
But LOOP is what I got used to, and its popularity is why it
got elevated into the ANSI standard.



(define (summer)
(let ((sum 0))
(case-lambda
(() sum)
((x) (set! sum (+ sum x)) sum)
((x . more) (set! sum (apply + sum x more)) sum))))

(define (counter)
(let ((count 0))
(case-lambda
(() count)
((x) (if x (set! count (+ count 1))) count))))

(define (make-extremizer comp)
(let ((extreme #f))
(case-lambda
(() extreme)
((x)
(if (or (not extreme) (comp x extreme))
(set! extreme x) extreme)))))

(define (maximizer :optional (comp >))
(make-extremizer comp))

(define (minimizer :optional (comp <))
(make-extremizer comp))

;; The name is borrowed from CLtL2, appendix B.
(define-syntax gathering
(syntax-rules ()
([_ ((name maker option ...) ...) body ...]
(let ( (name (maker option ...)) ... )
body ...))))


(define array-of-numbers #(55 0 2 99 42 47 83 37 68 39))

(gathering ((min minimizer) (max maximizer) (total summer) (count counter))
(vector-for-each
(lambda (x) (for-each (cut <> x) (list min max total count)))
array-of-numbers)
(list (min) (max) (/ (total) (count))))

===>
(0 99 236/5)


>
> (loop for w across widgets count (good-widget-p w))

(use srfi-43 :only (vector-count))

(vector-count good-widget? widgets)


--
The struggle of our time is to concentrate, not to dissipate: to renew our
association with traditional wisdom: to re-establish a vital connection between
the individual and the race. It is, in a word, a struggle against Liberalism.
--- T. S. Elliot