Discussion:
class slots initialisation using class slots
(too old to reply)
Nelson Alexandra
2020-05-27 11:27:10 UTC
Permalink
Given

(defstruct a-cell data next)

(defstruct a-list
(head (make-a-cell) :type a-cell)
(tail (make-a-cell) :type a-cell))

It is meant as a model of singly-linked lists. When creating a-list with

(let ((lst (make-a-list))) lst)

the lst represents an empty list. head and tail are dummy cell's just
for managing.

A first list item (let ((x (make-a-cell))) x) would be consed into the
list such that head.next points to x and x.next points to tail.

My Problem:
After creating an empty list with (make-a-list) head.next should point
to tail and tail.next should points to head (via their next slots).

+----------------+
v |
head ---------> tail

But after (make-a-list) head.next and tail.next are null.

When instead using

(defclass a-cell ()
((data :initarg :data :initform nil :accessor data)
(next :initarg :next :initform nil :accessor next)))

(defclass a-list ()
((head :initform (make-instance 'cell) :accessor head)
(tail :initform (make-instance 'cell) :accessor tail)))

the initialisation as intended could be done using

(defmethod initialize-instance :after ((l a-list) &key)
(setf (next (head l)) (tail l))
(setf (next (tail l)) (head l)))

My question:

Is this kind of initialisation as in initialize-instance where I use
slots to initialise slots also possible for the struct version above?
Lieven Marchand
2020-05-27 21:55:19 UTC
Permalink
Post by Nelson Alexandra
Is this kind of initialisation as in initialize-instance where I use
slots to initialise slots also possible for the struct version above?
The easiest way is to pass a :constructor nil argument to defstruct and
write your own make-a-list. I think it can also be done by some boa
lambda list trickery.
--
Laat hulle almal sterf. Ek is tevrede om die wêreld te sien brand en die vallende
konings te spot. Ek en my aasdier sal loop op die as van die verwoeste aarde.
Nelson Alexandra
2020-05-27 22:59:13 UTC
Permalink
Post by Lieven Marchand
[...]
The easiest way is to pass a :constructor nil argument to defstruct and
write your own make-a-list. I think it can also be done by some boa
lambda list trickery.
Thank you for the tip.

Loading...