从 Common LISP 中的结构本身访问结构字段

Accessing structure fields from the structure itself in Common LISP

对于我的项目,我特别需要一个具有(除其他外)2 个插槽的结构:

该函数槽必须评估当前状态,并return基于它的结果。但是,我找不到如何正确执行此操作。这是我的一段代码。

(defstruct state moves-left)

(defstruct problem
    (current-state)
    (solution (function (lambda () (null (state-moves-left :current-state)))))
)

编译时没有错误,但是当我解释这个时它们发生了:

> (setq p0 (make-problem :current-state (make-state)))
> (funcall (problem-solution p0))

SYSTEM::%STRUCTURE-REF: :CURRENT-STATE is not a structure of type STATE

有人知道怎么解决吗?我一般都是用常用的函数,但是这些结构和槽是硬性要求

编辑:感谢您的回答。在了解到这是不可能的之后,我更彻底地重新阅读了要求并发布了答案 .

错误的原因是 Common Lisp 中的结构不能用作 类: 在槽的函数默认值中 solution 无法引用槽的槽结构本身(正如您尝试使用 (state-moves-left :current-state).

如果你坚持使用结构体而不是类,一种可能是用参数定义函数,并在调用函数时传递结构体本身。类似于:

(defstruct problem
    (current-state)
    (solution (function (lambda (p) (null (state-moves-left p))))))

(let ((p0 (make-problem :current-state (make-state))))
  (funcall (problem-solution p0) p0))

您可以有一个单独的 create 函数:

(defun create-problem (state)
  (let ((problem (make-problem :current-state state)))
    (setf (problem-solution problem)
          (lambda ()
            (null (state-moves-left (problem-current-state problem)))))
    problem))

但是:为什么不直接使用 function/method?

(defmethod problem-solution ((p problem))
  (null (state-moves-left (problem-current-state p))))

在了解到这是不可能的之后,我更彻底地重新阅读了需求,发现这个函数实际上会接收一个参数(一个状态)。所以,代码现在可以工作了:

(解构问题 (当前状态) (解决方案(函数(lambda(state)(不是(null(state-moves-left state)))))) )