Scheme Syntax Help: Using a function that I have defined in another program

249 Views Asked by At

I have created two functions to help me solve my Subset sum problem. I seem to be getting an error though. It tells me that I am passing two arguments to list-sum. I've been fooling around with this program for several hours now. I was wondering if anyone could spot the problem.

This is my list-sum:

(define list-sum 
  (lambda(lst)
    (cond
      ((null? lst) 0)
      ((pair? (car lst))
       (+(list-sum (car lst)) (list-sum (cdr lst))))
      (else
       (+ (car lst) (list-sum (cdr lst)))))))

This is my function that uses list-sum:

(define ssum
  (lambda (n l)
    (cond
      ((null? l) #f)
      ((=(-(- n (car l))(list-sum l)) 0) l)
      ((ssum (cons (car l)) (cdr (cdr l))))
      (else (ssum n (cdr l))))))

It tells me that I have called "compound-procedure #(number) ssum" with one argument and that it requires two arguments. I am passing it as (ssum 8 (list 1 3 5 7)).

My questions are:

  1. Have I set up my functions correctly?
  2. Is there an easier method of summing the numbers of a list inside my ssum?
  3. I am also very new to Scheme. If you see an obvious way of shortening the code, please feel free to correct me.
2

There are 2 best solutions below

1
On

The list-sum function can be optimized. First it is possible to join the two (list-sum (cdr lst)) expressions and it is possible to reduce the three (car lst) expressions to one:

(define (list-sum lst)
  (if (null? lst)
      0
      (+ (let ((l (car lst)))
           (if (pair? l)
               (list-sum l)
               l))
         (list-sum (cdr lst)))))
0
On

I strongly recommend you to try racket, its IDE has this awesome debugger that only the ODB could claim being better.

I didn't dig too deep in how your code is supposed to work, because there are actually several errors in the ((ssum (cons (car l)) (cdr (cdr l)))) line: you call cons with only one argument, but you also have only one form in this cond clause, whereas it should have a test and at least one expression behind.