简体   繁体   中英

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

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)

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. 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. 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; simply pass f around as a parameter taking care of correctly advancing the recursion.

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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