Path: utzoo!mnetor!uunet!seismo!sundc!pitstop!sun!quintus!ok From: ok@quintus.UUCP (Richard A. O'Keefe) Newsgroups: comp.lang.lisp Subject: Re: CL question - conditional list elements Message-ID: <589@cresswell.quintus.UUCP> Date: 28 Jan 88 04:03:31 GMT References: <1350005@otter.HP.COM> Organization: Quintus Computer Systems, Mountain View, CA Lines: 49 Summary: use a macro In article <1350005@otter.HP.COM>, kers@otter.HP.COM (Christopher Dollin) writes: > Another question about idimatic and efficient code in CL. > > Suppose I wish to constrauct a list with conditional components, that is, > components that may or may not be absent. [The actual application I had > with this in was constructing a list of menu items, where some items were > only appropriate in certain circumstances]. > > The nearest I seem to be able to get is > > (append > ... list of some boring bits ... > (if Condition1 Bit1 '()) > ... list of more boring bits ... > (if Condition2 Bit2 '()) > .... list of yet more boring bits ... > ) > > or some splicing version likely to compile to similar code. This doesnt seem > too efficient (or nice to write, either!), even using -nconc- rather than > -append- - any comments, suggestions, or whatever? > Why not use a macro, such as (defmacro maybe-cons (Test Datum Rest) ; tested in `(let ((my:R ,Rest)) ; Xlisp 1.6 (if ,Test (cons ,Datum my:R) my:R))) and then do (cons boring-bit-a (maybe-cons condition-1 bit-1 (cons boring-bit-b (maybe-cons condition-2 bit-2 (cons boring-bit-c nil))))) This results in a pile of parens at the end, which is no problem with a structure editor or paren-balancing, but if that's a problem, define a maybe-list macro with calls like (maybe-list boring-bit-a bit-1 :if condition-1 boring-bit-b bit-2 :if condition-2 boring-bit-c ) maybe-cons shows how to do this. Of course, it does result in the list elements being evaluated from right to left rather than from left to right, but that shouldn't be a problem.