Page 1 of 1

Summing sublists elements!!!

Posted: Mon Jun 21, 2010 5:50 pm
by filippomazzetti
Hi there! :)
I would like to know how can I sum the elements of several sublists while preserving them.
I have this: ((1 3 5) (2 4 1) (1 1)) and want to get this: ((9) (7) (2)).
What's the fastest way to do it? :roll:
Thanks in advance! ;)

Re: Summing sublists elements!!!

Posted: Mon Jun 21, 2010 7:31 pm
by nuntius
I recommend using DO, DOLIST, or LOOP with APPLY. You could also solve this with a simple recursion.

Re: Summing sublists elements!!!

Posted: Mon Jun 21, 2010 10:07 pm
by filippomazzetti
Thank you for your reply, nuntius! :D I would like to avoid recursions for now (I'm afraid of getting lost). Could you please give me an example of how to apply your suggestions in a code? Please forgive my newbeness :?
Thanks in advance! ;)
nuntius wrote:I recommend using DO, DOLIST, or LOOP with APPLY. You could also solve this with a simple recursion.

Re: Summing sublists elements!!!

Posted: Tue Jun 22, 2010 1:50 am
by lispamour
filippomazzetti wrote:Hi there! :)
I would like to know how can I sum the elements of several sublists while preserving them.
I have this: ((1 3 5) (2 4 1) (1 1)) and want to get this: ((9) (7) (2)).
What's the fastest way to do it? :roll:
Thanks in advance! ;)
Remember that + can take several operands. Eg:

(+ 1 2) => 3

(+ 1 2 3) => 6

Now try MAPCAR and supply a LAMBDA function which uses APPLY of the + operator to each of the sublists.

I would write it out, but this seems a little too much like a homework problem, so I'll leave it to you to fill in the details. :)

Re: Summing sublists elements!!!

Posted: Tue Jun 22, 2010 8:43 am
by filippomazzetti
Thank you for your reply, lispamour! :D
I will try it today and get back here! ;)