Search code examples
common-lisp

Accessing structure fields from the structure itself in Common LISP


For my project, I specifically need a structure that has (among other things) 2 slots:

  • one holds data (current-state, a structure)
  • one holds a function (is-state-a-solution)

That function slot must evaluate the current-state and return a result based on it. However, I can't find how to do this properly. Here's a segment of my code.

(defstruct state moves-left)

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

No errors on compiling, but they happen when I interpret this:

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

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

Anyone knows how to solve this? I usually just use common functions, but these structure and slots are hard requirements.

EDIT: thanks for the answers. After learning this was impossible, I reread the requirements more thoroughly and posted the answer here.


Solution

  • After learning this was impossible, I reread the requirements more thoroughly and found out this function will actually receive an argument (a state). So, the code now works:

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