简体   繁体   English

计算平均值或Scheme中带字母的列表 - Dr.Racket

[英]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. 你可以将my-filter fn的结果传递给avg fn。

Also, the if statement finds if the list is empty; 此外,if语句查找列表是否为空; 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). 此外,avg函数应该处理除以0,这将在第三个示例中发生(当列表中没有数字时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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