Newsgroups: comp.lang.lisp Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!think.com!barmar From: barmar@think.com (Barry Margolin) Subject: Re: Help with Common lisp equivelence... Message-ID: <1991Apr7.101413.21482@Think.COM> Sender: news@Think.COM Organization: Thinking Machines Corporation, Cambridge MA, USA References: <1991Apr7.065143.5179@news.iastate.edu> Date: Sun, 7 Apr 91 10:14:13 GMT In article <1991Apr7.065143.5179@news.iastate.edu> tnbf6@CCVAX.IASTATE.EDU writes: >I was wondering if anyone could give me a lisp defintion of >(DEFSTRUCT ) Thanks... A suggestion of a good >source book would be fine as well... A complete definition of Common Lisp DEFSTRUCT is not possible using only portable Common Lisp. When the :TYPE option is not specified, DEFSTRUCT defines an implementation-specific data type, and there are no portable interfaces for creating or accessing objects of such types (well, if you have CLOS you may be able to do it using the meta-object protocol and the STRUCTURE-CLASS metaclass). Defining a simple DEFSTRUCT is a good exercise if you're interested in learning to write macros. Adding all the options is then a matter of incremental refinement. Here's the beginning of one that uses arrays as the representation: (defmacro defstruct (structure-name &rest slot-names) (let ((name-string (symbol-name structure-name))) `(progn (defun ,(intern (concatenate 'string "MAKE-" name-string)) (&key .,slot-names) (make-array ,(length slot-names) :initial-contents (list .,slot-names))) ,.(loop for i upfrom 0 for slot in slot-names for accessor = (intern (concatenate 'string name-string "-" (symbol-name slot))) collect `(defun ,accessor (,structure-name) (aref ,structure-name ,i)) collect `(defsetf ,accessor (,structure-name) (value) `(setf (aref ,,structure-name ,',i) ,value))) ',structure-name))) As you can see, the definition of DEFSTRUCT makes use of several of the more advanced features of Lisp macros and the backquote mechanism. Throw in support for a few of DEFSTRUCT's options and you'll really learn how powerful (and confusing) this stuff can be. -- Barry Margolin, Thinking Machines Corp. barmar@think.com {uunet,harvard}!think!barmar