Finding the 'sum' within a loop

Discussion of Common Lisp

Finding the 'sum' within a loop

Postby 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?
User avatar
I X Code X 1
 
Posts: 59
Joined: Sun May 29, 2011 8:52 pm
Location: NY

Re: Finding the 'sum' within a loop

Postby 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)))
Ramarren
 
Posts: 613
Joined: Sun Jun 29, 2008 4:02 am
Location: Warsaw, Poland

Re: Finding the 'sum' within a loop

Postby 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
User avatar
I X Code X 1
 
Posts: 59
Joined: Sun May 29, 2011 8:52 pm
Location: NY


Return to Common Lisp

Who is online

Users browsing this forum: Google [Bot] and 2 guests

cron