home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!think.com!barmar
- From: barmar@think.com (Barry Margolin)
- Newsgroups: comp.lang.lisp
- Subject: Re: Elegant control structure wanted
- Date: 19 Nov 1992 21:33:15 GMT
- Organization: Thinking Machines Corporation, Cambridge MA, USA
- Lines: 54
- Message-ID: <1eh16rINNl8i@early-bird.think.com>
- References: <98373@netnews.upenn.edu>
- NNTP-Posting-Host: telecaster.think.com
-
- In article <98373@netnews.upenn.edu> zaidel@muzungu.cis.upenn.edu (Martin J. Zaidel) writes:
- >(defun node-equal (node1 node2)
- > (and (unless (slot1-equal slot1 slot2)
- > (format t "Slot 1 not equal"))
- > (unless (slot2-equal slot1 slot2)
- > (format t "Slot 2 not equal"))
- > (unless (slot3-equal slot1 slot2)
- > (format t "Slot 3 not equal"))))
- >
- >This won't work, since UNLESS will return NIL, regardless of the
- >value of the slot-equal test.
-
- You can use OR instead of UNLESS; in fact, this is what people did all the
- time before UNLESS was introduced. The code then becomes
-
- (defun node-equal (node1 node2)
- (and (or (slot1-equal node1 node2)
- (format t "~&Slot 1 not equal.~%"))
- (or (slot2-equal node1 node2)
- (format t "~&Slot 1 not equal.~%"))
- (or (slot3-equal node1 node2)
- (format t "~&Slot 1 not equal.~%"))))
-
- Actually, I prefer not to depend on the return value of FORMAT being NIL
- (because I don't remember whether such return values are guaranteed), so
- I'd probably write something like:
-
- (defun node-equal (node1 node2)
- (and (or (slot1-equal node1 node2)
- (progn (format t "~&Slot 1 not equal.~%")
- nil))
- (or (slot2-equal node1 node2)
- (progn (format t "~&Slot 1 not equal.~%")
- nil))
- (or (slot3-equal node1 node2)
- (progn (format t "~&Slot 1 not equal.~%")
- nil))))
-
- And now that the code is starting to look messy and repetitive, I'd
- probably turn the repetitive code into a local macro:
-
- (defun node-equal (node1 node2)
- (macrolet ((compare (tester slot-number)
- `(or (,tester node1 node2)
- (progn (format t "~&Slot ~D not equal.~%" ,slot-number)
- nil))))
- (and (compare slot1-equal 1)
- (compare slot2-equal 2)
- (compare slot3-equal 3))))
- --
- Barry Margolin
- System Manager, Thinking Machines Corp.
-
- barmar@think.com {uunet,harvard}!think!barmar
-