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?
Thanks in advance!
Summing sublists elements!!!
Re: Summing sublists elements!!!
I recommend using DO, DOLIST, or LOOP with APPLY. You could also solve this with a simple recursion.
-
- Posts: 3
- Joined: Mon Jun 21, 2010 5:46 pm
Re: Summing sublists elements!!!
Thank you for your reply, nuntius! 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!
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!!!
Remember that + can take several operands. Eg: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?
Thanks in advance!
(+ 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.
-
- Posts: 3
- Joined: Mon Jun 21, 2010 5:46 pm
Re: Summing sublists elements!!!
Thank you for your reply, lispamour!
I will try it today and get back here!
I will try it today and get back here!