Three-way conditional for number signs on Lisp
Posted on
Updated on
A useful macro from Paul Graham’s On Lisp book:
After I looked at this macro, I started seeing opportunities to using it in many places, and yet I didn’t see anyone else using it.
The latest example I can think of is section 1.3.3 of Structure and Interpretation of Computer Programs, which I was reading recently:
1 2 3 4 5 6 7 8 9 10 |
(define (search f neg-point pos-point)
(let ((midpoint (average neg-point pos-point)))
(if (close-enough? neg-point post-point)
midpoint
(let ((test-value (f midpoint)))
(cond ((positive? test-value)
(search f neg-point midpoint))
((negative? test-value)
(search f midpoint pos-point))
(else midpoint))))))
|
Not that the book should introduce such macro this early, but I couldn’t avoid feeling bothered by not
using the nif macro, which could even remove the need for the intermediate
test-value variable:
It also avoids `cond’s extra clunky parentheses for grouping, which is unnecessary but built-in.
As a macro, I personally feel it tilts the balance towards expressivenes despite its extra cognitive load toll.