desireToLearn
desireToLearn

Reputation: 17

Creating a list of sums of lists in a list (Scheme)?

I'm not very familiar with Scheme, so I am having trouble with the problem.

Write a scheme procedure which takes a list of list of numbers each containing at least 1 number. Your procedure should return a list containing the individual sums of each of those lists of numbers. For example: ((1 2 3) (4 5) (6) (7 8 9 10)) -> (6 9 6 34)

So far I am trying to create a listCreator function and a sumHelper function. I'm still doing testing, but I'm getting stuck with an error.

    (define lst '((1 2 3) (4 5) (6) (7 8 9 10)))

    lst

    (define sumHelper
      (lambda (lst)
        (if (null? lst)
             0
             (+ (car lst) (sumHelper (cdr lst))))))

    (define listCreator
      (lambda (lst)
        (if (null? lst)
             0
             (sumHelper (car lst)))))

My error is: car: expects a pair, given 2

Any help or direction for solving this problem would be greatly appreciated.

Upvotes: 0

Views: 400

Answers (1)

Dan D.
Dan D.

Reputation: 74645

Your definition of listCreator didn't build nor apply itself to the rest of the list:

(define listCreator
  (lambda (lst)
    (if (null? lst)
         '()
         (cons (sumHelper (car lst)) (listCreator (cdr lst))))))

Also the value if the list is null should be the empty list: '() and not 0

Once these changes are made your code works as written.

Upvotes: 1

Related Questions