我不太确定自己在做什么错。我需要编写一个程序来过滤数字,使其低于数字列表的平均值,并且仅保留大于所有数字平均值的数字。
(define (total lon)
(cond
[(empty? lon) 0]
[else (+ first lon) (total (rest lon)))]))
(define (mean alon)
(/ (total alon) (length alon)))
(define (average-filter log)
(cond
[(empty? log) empty]
[(> (first log) (mean log))
(cons (first log) (average-filter (rest log)))]
[else (average-filter (rest log))]))
我希望它会删除所有低于平均值的内容,但最终会得到一个空列表。
前 (平均过滤器(列表1 2 3))->空 当我应该得到: (缺点3为空)
答案 0 :(得分:3)
由于log
在每次递归调用时都会缩小(mean log)
也会发生变化!
计算一次平均值:
(define (average-filter log)
(average-filter-h log (mean log)))
然后过滤更大的数字:
(define (average-filter-h log mean)
(cond
[(empty? log) empty]
[(> (first log) mean)
(cons (first log) (average-filter-h (rest log) mean))]
[else (average-filter-h (rest log) mean)]))
边注:
您还可以使用抽象将其更简洁:
(define (mean alon)
(/ (apply + alon) (length alon)))
(define (average-filter log)
(let ([m (mean log)])
(filter (λ (x) (> x m)) log)))