简体   繁体   English

Scheme中列出的值的总和

[英]Sum of values in a list squared in Scheme

I'm trying to have the following program work, but for some reason it keeps telling me that my input doesnt contain the correct amount of arguments, why? 我正在努力让以下程序工作,但由于某种原因,它一直告诉我,我的输入不包含正确数量的参数,为什么? here is the program 这是程序

(define (sum f lst)
   (cond
     ((null? lst)
       0)
     ((pair? (car lst))
      (+(f(sum (f car lst))) (f(sum (f cdr lst)))))
     (else
       (+ (f(car lst)) (f(sum (f cdr lst)))))))

and here is my input: (sum (lambda (x) (* xx)) '(1 2 3)) 这是我的输入: (sum (lambda (x) (* xx)) '(1 2 3))

Thanks! 谢谢!

btw I take no credit for the code, Im just having fun with this one (http://groups.engin.umd.umich.edu/CIS/course.des/cis400/scheme/listsum.htm) 顺便说一句,我不相信代码,我只是玩这个(http://groups.engin.umd.umich.edu/CIS/course.des/cis400/scheme/listsum.htm)

You're indeed passing the wrong number of arguments to the procedures sum and f , notice that the expressions (sum (f car lst)) , (sum (f cdr lst)) are wrong, surely you meant (sum f (car lst)) , (sum f (cdr lst)) - you don't want to apply f (a single-parameter procedure) to the two parameters that you're passing, and sum expects two arguments, but only one is passed. 你确实将错误数量的参数传递给了程序sumf ,注意表达式(sum (f car lst))(sum (f cdr lst))是错误的,你的意思是肯定的(sum f (car lst))(sum f (cdr lst)) - 你不想将f (单参数过程)应用于你传递的两个参数, sum需要两个参数,但只传递一个参数。 Try this instead: 试试这个:

(define (sum f lst)
  (cond ((null? lst)
         0)
        ((pair? (car lst))
         (+ (sum f (car lst)) (sum f (cdr lst))))
        (else
         (+ (f (car lst)) (sum f (cdr lst))))))

More important: you're calling the f procedure in the wrong places. 更重要的是:你在错误的地方调用f程序。 Only one call is needed in the last line, for the case when (car lst) is just a number and not a list - in the other places, both (car lst) and (cdr lst) are lists that need to be traversed; 在最后一行中只需要一次调用,对于(car lst)只是一个数字而不是列表的情况 - 在其他地方, (car lst)(cdr lst)都是需要遍历的列表; simply pass f around as a parameter taking care of correctly advancing the recursion. 简单地传递f作为参数,正确地推进递归。

Let's try the corrected procedure with a more interesting input - as it is, the procedure is capable of finding the sum of a list of arbitrarily nested lists: 让我们尝试使用更有趣的输入更正过程 - 实际上,该过程能够找到任意嵌套列表列表的总和:

(sum (lambda (x) (* x x)) '(1 (2) (3 (4)) 5))
> 55

You should take a look at either The Little Schemer or How to Design Programs , both books will teach you how to structure the solution for this kind of recursive problems over lists of lists. 您应该看一下The Little SchemerHow to Design Programs ,这两本书将教您如何在列表列表中构建解决此类递归问题的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM