Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!wuarchive!m.cs.uiuc.edu!ibma0.cs.uiuc.edu!sunc4.cs.uiuc.edu!epstein From: epstein@sunc4.cs.uiuc.edu (Milt Epstein) Newsgroups: comp.lang.lisp Subject: Re: Accessing a field of a Lisp structure Message-ID: <28047A1F.44CE@ibma0.cs.uiuc.edu> Date: 11 Apr 91 15:00:47 GMT References: <1991Apr10.215214.2827@cbnewsl.att.com> Sender: news@ibma0.cs.uiuc.edu Distribution: usa Organization: University of Illinois at Urbana-Champaign Lines: 52 In <1991Apr10.215214.2827@cbnewsl.att.com> davel@cbnewsl.att.com (David Loewenstern) writes: >In article mzaik@ee.eng.ohio-state.edu (Tahsin Mzaik) writes: >> >>I would like to write a macro that can access a particular field >>in a structure. >> >>Example: Let the structure be: >> (defstruct test a b c) >> >> (make-test instance) >> >>I would like to wite a macro 'access-field' that I can invoke >>something like >> >> (access-field instance 'a) > >Try: >(defmacro access-field (instance field) > `(,(intern (format nil "~A-~A" 'test field)) ,instance)) > >Note that this will allow >(access-field instance a) >to work but not, for example >(access-field instance (get-slot-name-from-some-wierd-place)) Someone else also posted this question just a couple of days ago, to which Barry Margolin responded suggesting a function like: (defun access-field (instance field) (case field (a (test-a instance)) (b (test-b instance)) (c (test-c instance)))) Note that if you use a function, it doesn't matter where you get the slot-name from. I sent a message to Barry suggesting the INTERN-FORMAT version, and he pointed out a couple of things: 1. It's better to use FIND-SYMBOL than INTERN, since the symbol (the structure accessor function) should already exist. 2. The CASE version appeared to be much faster (he did some timing test on a Symbolics). -- Milt Epstein Department of Computer Science University of Illinois epstein@cs.uiuc.edu