Page 1 of 1

Finding the 'sum' within a loop

Posted: Thu Jun 30, 2011 10:18 pm
by I X Code X 1
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?

Re: Finding the 'sum' within a loop

Posted: Thu Jun 30, 2011 11:00 pm
by ramarren
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)))

Re: Finding the 'sum' within a loop

Posted: Fri Jul 01, 2011 6:15 am
by I X Code X 1
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