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
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:
cons
the current element with the result of the recursive call, when it makes sense to do it.