简体   繁体   中英

computing average or a list with letters in Scheme - Dr.Racket

i need help creating a function that will compute the average of a list that can also have letters in them. For example:

(mean '(1 2 3 4 5)); → 3
(mean '(1 a 2 b c d e 3)); → 2
(mean '(a b c d e)); → "Error: no numbers in list"

So far this is what i have, but i get this error that i don't understand:

(define new_list '())

(define (mean lis)
  (if (null? lis)
      (display "Error: no numbers in list")
      (avg(set! new_list (my-filter number? lis))) ;my-filter, filters out everything except numbers
  )
)

(define (avg lis)
  (/ (apply + lis) (length lis)))

error msg i get:

mcar: contract violation
expected: mpair?
given: #<void>

Any help would be greatly apriciated

; mean-of-numbers computes the mean of a list of numbers (only)
(define (mean-of-numbers xs) ...)

; mean computes the mean of the numbers of the list xs ignoring other values
(define (mean xs) 
  (mean-of-numbers (filter number? xs))

Error is in following line:

(avg(set! new_list (my-filter number? lis))) ;my-filter, filters out everything except numbers

You do not need to set! any new list. You can just pass result of my-filter fn to avg fn.

Also, the if statement finds if the list is empty; not if there is no number in the list. Hence, the error message ("Error: no numbers in list") needs to be corrected.

Additionally, the avg function should handle division by 0, as will occur in your third example (when there is no number in the list).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM