Scheme function for adding elements in nested list

77 Views Asked by At

I'm trying to create a scheme program that adds the elements of a given list (both simple and nested).


(define (adder a_list)
  (cond
    ((null? a_list) 0)
    ((list? (car a_list))(adder (car a_list)))
    (else (+ (car a_list) (adder (cdr a_list))))
    )
  )

(adder '(2 (5 4) 6))```

The problem I'm running into is that when I run this, it only adds (5+4) + 2, and then doesn't add the 6. So my output is 11 rather than 17. I know my null statement at the top is causing this issue, but when I take it out I get this error:

  car: contract violation
  expected: pair?
  given: '()

Any tips would be greatly appreciated.

1

There are 1 best solutions below

2
alinsoar On
(define (adder a*)
  (if (null? a*)
      0
      (+ (if (pair? (car a*))
             (adder (car a*))
             (car a*))
         (adder (cdr a*)))))

And, shorter:

(define ++
  (lambda (a*)
    (fold-left (lambda (a x)
                 (+ a (if (pair? x) (++ x) x)))
               0
               a*)))

(written in mit/scheme)