Lisp function call error

拈花ヽ惹草 提交于 2019-12-01 21:12:13

问题


I've written a Lisp function like this:

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

When I try to call it, however, 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 it two arguments, it thinks I gave it one. If I give it three, it thinks I gave it three. If I give it one, it thinks I gave it one...


回答1:


It is the recursive call that only has one argument:

(power (- exponent 1))

It should be like this:

(power base (- exponent 1))



回答2:


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

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

should be:

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




回答3:


Compile your functions. In LispWorks use c-sh-c to compile a definition in the 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 Listener (the REPL) does not compile. You have to compile the definitions you enter at the Listener with the function COMPILE. Alternatively you can type the definitions into an editor window and compile it from there (by either compiling the file, the buffer or the expression). LispWorks also has features to locate code where an error happens.




回答4:


Lisp comes with the function expt, so no need to define your own.

(Unless this is an exercise or homework, in which case you might want to look at more efficient methods, such as exponentiation by squaring.)



来源:https://stackoverflow.com/questions/4222177/lisp-function-call-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!