User:Eriksiers/Alternate CLISP exponentiation

From Rosetta Code
Revision as of 01:39, 8 October 2011 by Eriksiers (talk | contribs) (created)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
This example was written by a novice in Common Lisp. If you are familiar with Common Lisp, please review and edit this example and remove this message. If the example does not work and you cannot fix it, replace this message with {{incorrect|Common Lisp|description of problem as you see it}}. If the code is correct but unidiomatic and you cannot fix it, replace this message with {{improve|Common Lisp|description of how it should be improved}}.


I wrote this while reading the first few chapters of Practical Common Lisp. (I'm about halfway through chapter 4 right now.) It seems to work -- at least for me, using CLISP -- and I think it might be a better version than the "real" solution provided at Exponentiation operator#Common Lisp, but I'm still way too green to know for sure. (This version can handle negative values of b, whereas that version can't -- I think.)

FWIW, I wrote this before looking at the Exponentiation operator page. Yay me.

Later, I might update this to handle b as a float.

<lang lisp>; calculates a to the bth power (a^b)

b must be an integer
a can be integer or floating-point
either or both can be negative
limits determined by lisp, I suppose -- arbitrary? none? I don't know

(defun ^ (a b)

   (if
       (> b 0)
       (* a
           (^ a
               (- b 1)
           )
       )
       (if
           (< b 0)
           (/ 1
               (^ a
                   (- 0 b)
               )
           )
           (if (= b 0) 1)
       )
   )

)</lang>

Sample outputs:

CL-USER> (^ 1.1 2)
1.21
CL-USER> (^ -1 2)
1
CL-USER> (^ -1 3)
-1
CL-USER> (^ -1.1 -1)
-0.9090909
CL-USER> (^ 2 300)
2037035976334486086268445688409378161051468393665936250636140449354381299763336706183397376
CL-USER> (^ 1 .5)
; Evaluation aborted on NIL.