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.

Finding the 'sum' within a loop

3 posts · 1211 views

Hello, I have this piece of code:
(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:
(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

LOOP is expression as any other. You can just do:
(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:
(loop for x from 1 to 10
      sum x into sum
      finally (return (expt sum 2)))

Re: Finding the 'sum' within a loop

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