DrRacket - 显示列表中高于平均值的所有值 [英] DrRacket - Display all the values in a list that are above average

查看:24
本文介绍了DrRacket - 显示列表中高于平均值的所有值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个函数,该函数使用数字列表并生成列表中高于平均值的元素.下面是我的代码:

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))])))

很明显我的代码有问题......有人可以帮助我吗?(average-filter (cons 40 (cons 30 empty)) 的错误信息是:

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:

缺点:需要 2 个参数,但只找到 1 个

cons: expects 2 arguments, but found only 1

推荐答案

几点意见:在average过程中,分母不需要加1,但你应该处理这种情况当它为零时.另请注意,您可以通过仅计算一次 average 来改进您的解决方案,它对于输入列表将是相同的,因此您无需在每次迭代时重新计算它.并且请不要调用您的参数 listlog,它们会与现有程序发生冲突.

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.

现在关于 average-filter 的真正问题:它与您上一个问题的错误相同,您必须不要cons 部分放在一开始,这不是它的工作方式.您应该使用当前元素和递归调用的结果调用cons,以构建一个包含结果的列表.而且你必须有一个基本情况,想想看:当你用完要遍历的元素时会发生什么?这就是您需要返回空列表的地方:

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. 处理输入列表为空的情况.
  2. cons 当前元素与递归调用的结果,如果这样做是有意义的.
  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.

这篇关于DrRacket - 显示列表中高于平均值的所有值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆