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

前端 未结 1 1923
时光取名叫无心
时光取名叫无心 2021-01-28 02:35

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         


        
1条回答
  •  情歌与酒
    2021-01-28 02:55

    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.

    0 讨论(0)
提交回复
热议问题