Sujet : Re: Finding Average without using Recusrion only using Prog
De : HenHanna (at) *nospam* devnull.tb (HenHanna)
Groupes : comp.lang.lispDate : 16. Jun 2024, 20:28:23
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <v4nas9$5tka$1@dont-email.me>
References : 1
User-Agent : Mozilla Thunderbird
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 '())