Path: ...!feed.opticnetworks.net!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: HenHanna Newsgroups: comp.lang.lisp Subject: Re: Finding Average without using Recusrion only using Prog Date: Sun, 16 Jun 2024 12:48:24 -0700 Organization: A noiseless patient Spider Lines: 53 Message-ID: References: MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 8bit Injection-Date: Sun, 16 Jun 2024 21:48:27 +0200 (CEST) Injection-Info: dont-email.me; posting-host="15d315eb6699321768c126a81b6bef90"; logging-data="226947"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX190CgUY48ISeE575o6whXdGtSmVMNM4bJI=" User-Agent: Mozilla Thunderbird Cancel-Lock: sha1:psZ+Q+BvfpVEujn9DeaIqOaqzoY= In-Reply-To: Content-Language: en-US Bytes: 2345 On 6/16/2024 11:28 AM, HenHanna wrote: > On 6/15/2024 9:39 PM, B. Pym wrote: >>>      (defun avg (args) >>>        (loop for x in args >>>            for l upfrom 1 >>>            summing x into tot >>>            finally (return (/ tot l)))) >> >> Gauche Scheme >> >> (use gauche.collection) ;; fold2 >> >> (define (add&count n sum cnt) (values (+ sum n) (+ cnt 1))) >> >> (define (avg nums) >>    (apply / >>      (values->list >>        (fold2 >>          add&count >>          0 0 >>          nums)))) >> >> (avg '(20 30 40 50 60 70 80))     ===>   50 > > > Nice...    Here's a more boring version: > > > (define (ave x) >   (let ((L (length x))) >     (if (> L 0) >       (/ (fold + 0 x) L)))) > > (define (Pave x)   (format #t "~%    ~S  ~S  ~%" x (ave x))) > > (Pave  '(1 2 3)) > (Pave  '(1 2 3 4)) > (Pave  '(1)) > (Pave  '()) > (define-macro (ave x) `(/ (+ ,@ (map (lambda (n) `(+ ,@ (make-list n 1))) (cadr x))) (+ ,@ (map (lambda (n) 1) (cadr x))))) (print (ave '(1))) (print (ave '(1 2 3))) gosh> (macroexpand '(ave '(1 2 3))) ==> (/ (+ (+ 1) (+ 1 1) (+ 1 1 1)) (+ 1 1 1))