我正在尝试用 lisp (ECL) 创建一个猜牌游戏。但是我收到错误。
(defun random-card ()
(coerce '(
(char (random 4) "SCDH")
(char (random 13) "A23456789JQK"))
'string)
)
(defun repeat (x n)
(if (zerop n)
nil
(cons (x) (repeat x (1- n)))))
(print (repeat #'random-card 3))
错误:
An error occurred during initialization:
The function X is undefined..
未定义的函数X是repeat的参数吗?我错过了什么?
Common Lisp 是 Lisp-2,这意味着函数和变量具有不同的命名空间。这就是为什么你必须写
#'random-card
而不仅仅是 random-card
。 random-card
作为参数在 value 命名空间中查找。 #'random-card
是 (function random-card)
的快捷方式,它在 function 命名空间中查找名称(function
本身不是 函数;它是极端 融入到Common Lisp 系统)。
因此
function
在函数命名空间中获取一个名称并将其绑定到一个值。现在,您的 x
函数中有一个名为 repeat
的值。 x
是值命名空间中的变量,当您编写 (x)
时,Common Lisp 会在 function 命名空间中查找。也就是说,它正在寻找经过 defun
ed、flet
ed 或 labels
ed 的内容。要调用存储在值级变量中的函数,我们使用 funcall
。
(defun repeat (x n)
(if (zerop n)
nil
(cons (funcall x) (repeat x (1- n)))))