Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!zaphod.mps.ohio-state.edu!think.com!barmar From: barmar@think.com (Barry Margolin) Newsgroups: comp.lang.lisp Subject: Re: structures Keywords: structures Message-ID: <1991Apr9.202146.18803@Think.COM> Date: 9 Apr 91 20:21:46 GMT References: <1991Apr09.091234.18122@kub.nl> Sender: news@Think.COM Organization: Thinking Machines Corporation, Cambridge MA, USA Lines: 57 In article <1991Apr09.091234.18122@kub.nl> pberck@kub.nl writes: >How can I 'choose slots' in a structure I have defined? Say I have the >structure (user) with the slots (name) and (adres), and I want >a function which accesses one of the two, supplied as an argument >to the function. (I hope I am making myself clear.) >For example: > >(defun prt (someone slot) > (print (user-slot someone))) > >I would like to supply 'name' or 'adres' as argument (slot) to the function. >How do I do this? I could probably set things up differently, but I >would like to do it this way :) If we had a FAQ list, this would certainly be on it (hmm, I could probably save myself lots of time by compiling a FAQ list, so maybe I will). There's currently no portable way to do this automatically. Eventually it will be doable using the CLOS metaobject protocol, though. Right now, the only thing you can do is write a function that manually selects between the slots, e.g.: (defun prt (someone slot) (print (ecase slot (name (user-name someone)) (adres (user-adres someone)))) You can also abstract this out so that you don't have to repeat it in different functions: (defun user-accessor (slot) (ecase slot (name #'user-name) (adres #'user-adres))) (defun user-setter (slot) (ecase slot (name #'(lambda (user new-value) (setf (user-name user) new-value))) (adres #'(lambda (user new-value) (setf (user-adres user) new-value))))) You can then write (defun prt (someone slot) (print (funcall (user-accessor slot) someone))) and (defun set-someone (someone slot value) (funcall (user-setter slot) someone value)) -- Barry Margolin, Thinking Machines Corp. barmar@think.com {uunet,harvard}!think!barmar