Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Re: Flatten function problem

20 views
Skip to first unread message

WJ

unread,
Apr 28, 2012, 11:37:56 PM4/28/12
to
Why this is marked as abuse? It has been marked as abuse.
Report not abuse
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

WJ

unread,
Apr 29, 2012, 12:11:52 AM4/29/12
to
Why this is marked as abuse? It has been marked as abuse.
Report not abuse
(define (sum-all xs)
(for/sum ([x xs]) (if (number? x) x (sum-all x))))

WJ

unread,
Dec 22, 2014, 3:18:24 AM12/22/14
to
Why this is marked as abuse? It has been marked as abuse.
Report not abuse
Gauche Scheme:

(use srfi-42)
(define (sum-all xs)
(sum-ec (: x xs) (if (number? x) x (sum-all x))))

(sum-all '(1 ((5 6 ) 3) (2)))
===>
17

WJ

unread,
Dec 16, 2015, 12:40:50 AM12/16/15
to
MatzLisp (Ruby):

[1, [[5, 6], 3], [2]].flatten.reduce(:+)
==>17

--
"If a government uses the instruments of power in its hands for the purpose of
leading a people to ruin, then rebellion is not only the right but also the
duty of every individual citizen."

Matthew Carter

unread,
Dec 16, 2015, 2:47:57 AM12/16/15
to
Gprolog (prolog):

reduce([], 0). reduce([H|T], S) :- reduce(T, R), S is H + R.
flatten([1, [[5, 6], 3], [2]], Y), reduce(Y, X).

--
Matthew Carter (m...@ahungry.com)
http://ahungry.com
0 new messages