Steve Gonedes wrote:
> "David Nixon" <
da...@nixon25.freeserve.co.uk> writes:
>
> < I have tried to construct a function that flattens a list and then adds the
> < contents eg
> < (flatten '(1 ((5 6) 3) (2))) produces (17). The problem is that I cannot get
> < it to add the list once it has been flattened. I have tested the flatten
> < function without adding the list members and it works fine, but I cannot get
> < it to add.
> < Any suggestions
> < (defun flatten (s)
> < (cond ((null s) 0)
> < ((atom s) (list s))
> < (t (append (flatten (car s)) (flatten (cdr s)) <= ok upto here
> < (apply '+ '(flatten s)))))) <= how do you add once
> < flattened
> <
> < (flatten '(1 ((5 6 ) 3) (2)))
>
> Rather than construct a new list then add the numbers you could just
> add the numbers as you recurse through the list. You just have to
> return 0 when you hit a nil (the end of the list usually). I think you
> got the harder part right (returning a zero), you just have to move
> the `+' function.
>
> (defun add-numbers (list)
> (cond ((null list) 0)
> ((atom list) list)
> (t (+ (add-numbers (first list))
> (add-numbers (rest list))))))
>
> (add-numbers '(1 ((5 6 ) 3) (2))) => 17
Racket:
(define (sum-all xs)
(foldl
(lambda(x sum)(+ sum (if (number? x) x (sum-all x))))
0
xs))
(sum-all '(1 ((5 6 ) 3) (2)))
=> 17