How to define structures in Lisp using parameters in a definition

I want to write Lisp code like this

(defstruct board (size 7) (matrix (make-array (list size size)) (red-stones 0) (black-stones 0)) 

to determine the structure representing the playing field.

I want to be able to create a new board with a breadboard that will create a matrix on the fly with a given size (size x size), so I do not need to call the make-board from another function that makes the matrix.

However, when I load this code into the clisp interpreter and try to create a new board (with make-board), I get an error message telling me that "size" does not matter.

Can structure fields be used in the structure definition itself?

Or should I do this?

 (defstruct board size matrix (red-stones 0) (black-stones 0)) (defun create-board (size) (make-board :size size :matrix (make-array (list size size))) ) 

Indeed, I do not like the availability of both a finished board and a created board, because this can lead to programming errors.

+4
source share
2 answers

You can use the boa constructor:

 (defstruct (board (:constructor make-board (&optional (size 7) &aux (matrix (make-array (list size size)))))) (size) (matrix) (red-stones 0) (black-stones 0)) 

CLHS documentation for defstruct and BOB lambda lists .

+2
source

Indeed, I do not like the availability of both a finished board and a created board, because this can lead to programming errors.

There is a fair point, but then, having size and matrix , both available can also lead to programming errors.

O (n) is not required to measure the size of the array, so I would just exclude the size slot. If you usually want this value for board , it's easy to create a simple wrapper function.

In case you want a more general solution "some of my slots are determined by some of my other slots," by Kenny Tilton Cells , although these days it doesn't look terribly active.

Finally, I would use defclass rather than defstruct if you have no reason for this.

+1
source

All Articles