Summing sublists elements!!!

Discussion of Common Lisp
Post Reply
filippomazzetti
Posts: 3
Joined: Mon Jun 21, 2010 5:46 pm

Summing sublists elements!!!

Post by filippomazzetti » Mon Jun 21, 2010 5:50 pm

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

nuntius
Posts: 538
Joined: Sat Aug 09, 2008 10:44 am
Location: Newton, MA

Re: Summing sublists elements!!!

Post by nuntius » Mon Jun 21, 2010 7:31 pm

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

filippomazzetti
Posts: 3
Joined: Mon Jun 21, 2010 5:46 pm

Re: Summing sublists elements!!!

Post by filippomazzetti » Mon Jun 21, 2010 10:07 pm

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.

lispamour
Posts: 18
Joined: Wed Jun 02, 2010 12:29 am

Re: Summing sublists elements!!!

Post by lispamour » Tue Jun 22, 2010 1:50 am

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. :)

filippomazzetti
Posts: 3
Joined: Mon Jun 21, 2010 5:46 pm

Re: Summing sublists elements!!!

Post by filippomazzetti » Tue Jun 22, 2010 8:43 am

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

Post Reply