Lisp function call error

I wrote the Lisp function as follows:

(defun power (base exponent) (if (= exponent 0) 1 (* base (power (- exponent 1))))) 

When I try to call it, I get some errors:

 CL-USER 2 > (power 2 3) Error: POWER got 1 arg, wanted at least 2. 1 (abort) Return to level 0. 2 Return to top loop level 0. Type :b for backtrace or :c <option number> to proceed. Type :bug-form "<subject>" for a bug report template or :? for other options. CL-USER 3 : 1 > (power 2) Error: POWER got 1 arg, wanted at least 2. 1 (abort) Return to level 1. 2 Return to debug level 1. 3 Return to level 0. 4 Return to top loop level 0. Type :b for backtrace or :c <option number> to proceed. Type :bug-form "<subject>" for a bug report template or :? for other options. CL-USER 4 : 2 > (power 2 3 4) Error: POWER got 3 args, wanted 2. 1 (continue) Ignore the extra arg. 2 (abort) Return to level 2. 3 Return to debug level 2. 4 Return to level 1. 5 Return to debug level 1. 6 Return to level 0. 7 Return to top loop level 0. Type :b for backtrace or :c <option number> to proceed. Type :bug-form "<subject>" for a bug report template or :? for other options. 

What's going on here? If I give him two arguments, he thinks I gave him this. If I give three, I think I gave three. If I give him one, he thinks I gave him one ...

+4
source share
4 answers

This is a recursive call that has only one argument:

 (power (- exponent 1)) 

It should be like this:

 (power base (- exponent 1)) 
+11
source

A recursive call is your problem. You forgot to pass the base as the first argument.

(* base (power (- exponent 1)))))

it should be:

(* base (power base (- exponent 1)))))

+6
source

Compile your functions. In LispWorks, use c-sh-c to compile the definition in an editor.

Here in the REPL:

 CL-USER 18 > (defun power (base exponent) (if (= exponent 0) 1 (* base (power (- exponent 1))))) POWER CL-USER 19 > (compile 'power) ;;;*** Warning in POWER: POWER is called with the ;;; wrong number of arguments: Got 1 wanted 2 

The compiler will already tell you that there is a problem with the code.

Note that the LispWorks (REPL) listener does not compile. You must compile the definitions you enter in the Listener using the COMPILE function. Alternatively, you can enter the definitions in the editor window and compile them there (by compiling the file, buffer, or expression). LispWorks also has functions for finding code where an error occurs.

+3
source

Lisp comes with an expt function, so you don't need to define your own.

(If this is an exercise or homework, in this case you may need more effective methods, such as squaring .)

+1
source

All Articles