Lisp function call error

后端 未结 4 551
傲寒
傲寒 2021-01-19 12:56

I\'ve written a Lisp function like this:

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

Wh

相关标签:
4条回答
  • 2021-01-19 13:27

    It is the recursive call that only has one argument:

    (power (- exponent 1))
    

    It should be like this:

    (power base (- exponent 1))
    
    0 讨论(0)
  • 2021-01-19 13:30

    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)))))

    0 讨论(0)
  • 2021-01-19 13:45

    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.)

    0 讨论(0)
  • 2021-01-19 13:53

    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.

    0 讨论(0)
提交回复
热议问题