Finding the 'sum' within a loop

Discussion of Common Lisp
Post Reply
I X Code X 1
Posts: 59
Joined: Sun May 29, 2011 8:52 pm
Location: NY
Contact:

Finding the 'sum' within a loop

Post by I X Code X 1 » Thu Jun 30, 2011 10:18 pm

Hello, I have this piece of code:

Code: Select all

(loop for x from 1 to 10    
      sum (* x x))
This returns 385, however, what I want it to do is get the sum from 1 to 10 (which is 55) and then do (* 55 55), which equals 3025. What I want it to do is (expt 55 2), but it must take the sum before it does the expt. The current code is taking the exponent of each and them summing the result.

I clearly would like to write:

Code: Select all

(loop for x from 1 to 10
      (expt (sum x) 2))
...but it does not work because 'sum' is part of the loop macro and not an actual function.


Btw, this is from Project Euler.


Any tips?

ramarren
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland
Contact:

Re: Finding the 'sum' within a loop

Post by ramarren » Thu Jun 30, 2011 11:00 pm

LOOP is expression as any other. You can just do:

Code: Select all

(expt (loop for x from 1 to 10
            sum x)
      2)
Remember that in Common Lisp (and most Lisps) everything is an expression and everything returns a value, except obviously non-local return constructs.

Another way to do this, which might be clearer in some circumstances, is to use the FINALLY clause:

Code: Select all

(loop for x from 1 to 10
      sum x into sum
      finally (return (expt sum 2)))

I X Code X 1
Posts: 59
Joined: Sun May 29, 2011 8:52 pm
Location: NY
Contact:

Re: Finding the 'sum' within a loop

Post by I X Code X 1 » Fri Jul 01, 2011 6:15 am

Thanks a lot, I should have thought about taking the expt of the enitre result outside of the loop. Now solved three of the problems from that site and all in 4 lines or under :D

Post Reply