Taking exponent of a number

Discussion of Common Lisp
Post Reply
SterlingM
Posts: 8
Joined: Sun Mar 21, 2010 8:18 pm

Taking exponent of a number

Post by SterlingM » Thu Sep 02, 2010 10:16 pm

I am trying to make a function to take the yth power of number n.

Code: Select all

(defun xp (x y)
                   (loop while (> 1 y) do
                         (setf x (* x x))
                         (setf y (- y 1))) (print x))
That is what I have now. Everytime I run the, the only output is whatever I enter for x, twice. Ex.

(xp 2 3) should print 8. Instead it just prints
2
2

(xp 10 2) should print 100. Instead it just prints
10
10

(xp 100 100) should print a huge number. Instead it just prints
100
100

Why is this?

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

Re: Taking exponent of a number

Post by ramarren » Thu Sep 02, 2010 11:05 pm

First, usually you don't want to print out the return value of a function, since the REPL will print it anyway, which is why you get the output echoed.

Your end condition is wrong since it says "execute the loop while one is greater than y", which is never true for your examples, so the value is never touched and returned as it was. Even if you fix that, it will not be exponentiation, since you are multiplying the modified value of x by itself, not by original.

Avoid using SETF. LOOP already has a large number of iteration constructs, which allow expressing state mutation in a structured way (I prefer iterate, code walking issues notwithstanding). Often it is possible to avoid a DO clause altogether.

Code: Select all

(defun xp (x y)
  (loop repeat y
        for xprime = x then (* xprime x)
        finally (return xprime)))

Tom
Posts: 22
Joined: Sat Jun 28, 2008 12:52 pm
Location: Wichita, KS
Contact:

Re: Taking exponent of a number

Post by Tom » Fri Sep 03, 2010 5:43 am

Just to be clear, you are writing your own exponent function for practice, right? Otherwise, you should use EXPT.

Good luck,

~ Tom

Post Reply