Generic lisp: slot value for structure structures

In general, lisp, what can I use to access the structure slot using the name of the slot / symbol?

I want

(defstruct point (x 0) (y 0)) (defmacro -> (struct slot) `(slot-value ,struct ,slot)) (setf p (make-point)) (setf (slot-value p 'x) 1) (setf (-> p 'y) 2) 

I use clozure cl, and in clozure cl this works. However, AFAIK is non-standard behavior (equivalent to C ++ “undefined behavior”). I don't plan on switching to another CL implementation, so should I continue to use slot-value for structures, or is there a better way to do this?

+7
source share
1 answer

Usually you should use access functions with structures.

Your code defines the access functions point-x and point-y . You can use them.

You can also use SLOT-VALUE with structures in implementations that support it. I assume most implementations (exception will be GCL). There is Lisp software that assumes SLOT-VALUE works for structures. I do not think that the implementation will remove support for it. This is not a standard because some developers would not like to provide this functionality in deployed applications.

So both ways are fine.

If you want to have short names, refer to the accessories:

 CL-USER 109 > (defstruct (point :conc-name) (x 0) (y 0)) POINT CL-USER 110 > (make-point :x 5 :y 3) #S(POINT :X 5 :Y 3) CL-USER 111 > (setf p1 *) #S(POINT :X 5 :Y 3) CL-USER 112 > (x p1) 5 CL-USER 113 > (setf p2 (make-point :x 2 :y 3)) #S(POINT :X 2 :Y 3) CL-USER 114 > (list p1 p2) (#S(POINT :X 5 :Y 3) #S(POINT :X 2 :Y 3)) CL-USER 115 > (mapcar 'x (list p1 p2)) (5 2) 

Name mappings between different access functions should then be prevented by the package.

If you want to write a shorter version of SLOT-VALUE , that's fine too. Write a macro. Or write a built-in function. Of course - why not?

As I said, SLOT-VALUE works with structures in most implementations. In this case, you do not care that the ANSI CL specification does not define this. In many implementations, the ANSI CL specification expands. For example, SLOT-VALUE works on structures, implementing streams as CLOS classes, implementing conditions as CLOS classes, providing Meta-object Protocol, ...

+8
source

All Articles