2

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.
YasirA
  • 9,531
  • 2
  • 40
  • 61
user614885
  • 141
  • 2
  • 2
  • 9
  • 4
    You do call it with only one argument, which is `(cons (car l) (cdr(cdr l)))`. – YasirA Feb 20 '11 at 08:03
  • Answering the question is better than editing the code. I tried to figure out whats wrong with the program and saw your comment ... later. – knivil Feb 20 '11 at 11:45
  • Thanks guys.I felt kind of silly after such an easy fix. The recursion is hurting my brain(haha). Thank you for your time though. – user614885 Feb 20 '11 at 23:03

2 Answers2

0

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.

Nowhere man
  • 5,007
  • 3
  • 28
  • 44
-1

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)))))
ceving
  • 21,900
  • 13
  • 104
  • 178
  • That hardly counts as optimization, it changes neither the speed nor the space usage of the function... Also, God kills a kitteh each time you use a first-letter variable. – Nowhere man Jul 15 '11 at 00:59