not*_*ing 0 lisp syntax-error user-defined-functions
我试图写一个递归代码,x^y但问题是如何更新代码它给我一个错误.
代码:
(defun power(x y) (if(> y 0) (* x (power(x (- y 1)))) (1)))
Run Code Online (Sandbox Code Playgroud)
错误:
CL-USER 11 : 5 >Power 2 3
Error: Undefined operator X in form (X (- Y 1)).
Run Code Online (Sandbox Code Playgroud)
错误:
CL-USER 11 : 5 >power(2 3)
Illegal argument in functor position: 2 in (2 3).
Run Code Online (Sandbox Code Playgroud)
sou*_*eck 13
你以错误的方式调用函数.在lisps中,函数调用具有以下形式:
(f a b c)
Run Code Online (Sandbox Code Playgroud)
不
f(a b c)
Run Code Online (Sandbox Code Playgroud)
你(power (x (- y 1)))的递归定义,(x (- y 1))因此错误:x不是一个函数.
使用,(power x (- y 1))所以你的定义变成:
(defun power (x y)
(if (> y 0)
(* x
(power x (- y 1)))
1))
Run Code Online (Sandbox Code Playgroud)
并称之为 (power 2 3)
要稍微扩展上一个(正确的)答案,此版本使用一些惯用函数:
(defun power (x y)
(if (plusp y)
(* x (power x (1- y)))
1))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9299 次 |
| 最近记录: |