This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Summing sublists elements!!!

5 posts · 1126 views

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!!!

I recommend using DO, DOLIST, or LOOP with APPLY. You could also solve this with a simple recursion.

Re: Summing sublists elements!!!

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!!!

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!!!

Thank you for your reply, lispamour! :D
I will try it today and get back here! ;)