I'm trying to write a function in scheme to average a list. So far I have a function that will add everything up, but that won't work. What I want to to is get the first and second from each list, add them up, and then call avg on the rest of the list. Any suggestions?
(define a 0)
(define (avg N)
(if (null? N)
0
(+ (car N) (avg (cdr N) ) )
))
Copyright © 2024 Q2A.MX - All rights reserved.
Answers & Comments
Verified answer
How is that first-second idea going to work any differently.
my version
(define (avg Ln) ;;list of numbers
(/ (sum-list Ln) ;;the function that you posted
(count Ln))) ;;sometimes included as a primitive or see below
That's going to be the most readable
could also call a helper function instead with an initial count.
(define (avg Ln)
(define (avg-helper Ln sum count)
(if (null? Ln)
(/ sum count)
(avg-helper (cdr Ln) (+ sum (car Ln)) (+ count 1))))
(if (null? Ln)
"No Average" ;;could throw an error if you knew how here
(avg-helper Ln 0 0)))
(define (count L)
(if (null? L)
0
(+ 1 (count (cdr L)))))