DrRacket - Display all the values in a list that are above average

不羁的心 提交于 2020-02-26 02:14:05

问题


I'm creating a function that consumes a list of numbers and produces the elements in the list that are above average. Below is my code:

(define (listlength list)
        (cond
            ((empty? list) 0)
            (else (+ 1 (listlength (rest list))))))

(define (listsum list)
  (cond
    [(empty? list) 0]
    [else (+ (first list)
             (listsum (rest list)))]))

(define (average log)
  (/ (listsum log) (+ (listlength log) 1)))

(define (average-filter log)
  (cons
  (cond
    [(> (first log) (average log)) (first log)]
    [else (average-filter (rest log))])))

So obviously there is something wrong with my code...Can someone help me? The error message for (average-filter (cons 40 (cons 30 empty) is:

cons: expects 2 arguments, but found only 1


回答1:


A couple of comments: in the average procedure, there's no need to add 1 to the denominator, but you should handle the case when it's zero. Also notice that you can improve your solution by calculating the average only once, it'll be the same for the input list, so you don't need to recalculate it at every iteration. And please don't call your parameters list or log, they will clash with existing procedures.

Now for the real issue with average-filter: it's the same error of your previous question, you must not put the cons part at the beginning, that's not how it works. You should call cons with the current element and the result of the recursive call, to build a list with the results. And you must have a base case, think about it: what would happen when you run out of elements to traverse? that's the point where you need to return an empty list:

(define (average-filter lst)
  (cond
    [(empty? lst) empty]
    [(> (first lst) (average lst))
     (cons (first lst) (average-filter (rest lst)))]
    [else (average-filter (rest lst))]))

Please, spend some time studying the proper way to build an output list as a result of traversing an input list, notice that you need to:

  1. Handle the case when the input list is empty.
  2. cons the current element with the result of the recursive call, when it makes sense to do it.


来源:https://stackoverflow.com/questions/58381946/drracket-display-all-the-values-in-a-list-that-are-above-average

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!