[plt-scheme] How to change the following code to make it handle nested lists?

From: Eli Barzilay (eli at barzilay.org)
Date: Tue Nov 25 07:28:20 EST 2008

On Nov 23, SamuelXiao wrote:
> I have following code:
> 
> (define (mysum list)
>    (if (null? list)
>        0
>       (+ (car list) (mysum (cdr list)))
>     )
> )
> 
> It can handle the case summing up a list of numbers....however, I want
> to handle case like '(1 (2 3) 4), how can I make it?
> The code can handle (mysum '(1 2 3)) => 6, but when it comes to (mysum
> '(1 (2 3) 4))=>error.  Any help would be appreciated.

(require scheme/list)
(define (mysum list) (foldl + 0 (flatten list)))

-- 
          ((lambda (x) (x x)) (lambda (x) (x x)))          Eli Barzilay:
                  http://www.barzilay.org/                 Maze is Life!


Posted on the users mailing list.