Writing code in thinking order

I took a detour from Seibel’s book to try out this neat little Head First-like Lisp tutorial.

In it, there’s some sample data:

(setf *map* '((living-room (you are in the living-room of a wizards house. there is a wizard snoring loudly on the couch.)
                           (west door garden)  
                           (upstairs stairway attic))
              (garden (you are in a beautiful garden. there is a well in front of you.)
                      (east door living-room))
              (attic (you are in the attic of the wizards house. there is a giant welding torch in the corner.)
                     (downstairs stairway living-room))))

And a function for accessing part of that data:

(defun describe-location (location map)
  (second (assoc location map)))

The second function grabs the second item in the list returned by (assoc location map). What bothers me initially is that the order in which I have to write this seems to be the reverse of the order in which I would think through the problem. For example, if I wanted to get the description of the living room, I would think “First, get the *map*. Then, look inside it for the living room. Finally, grab the second item in the living-room list.” This is the way it works in XPath. If the sample data was XML, then an XPath expression for getting the living room description might look like this:

/map/*[@name=$location]/*[2]

Start with the map, then get location, then get the second item inside that. (Also, one nice thing about XPath 2.0 is that path expressions are generalized for function application. You can write get-map()/get-location()/get-second-item(), which works the same way in this case because each step returns a 1-item list.)

Anyway, I’m sure there’s probably another way to write such Lisp expressions that doesn’t require me to think backwards and—worse yet—keep all the steps in my head at once. Maybe an object-oriented approach is all that’s needed a la map.getLocation().getSecond() (like in Java). Short of that, I could always bind temporary results to variables and build up the function calls from that. But I really don’t like being forced to create variables just so I can write the code in the order that seems natural.

Maybe I just need to reverse my thinking. Maybe this has something to do with what Paul Graham refers to as “bottom-up programming”. I don’t know.

Speaking of the Head First series, Kathy Sierra just posted “The Clueless Manifesto”. In the spirit of that, I intend to ask even more dumb questions as I continue to learn Lisp. I may want to teach this stuff some day, and this will be a record of what it was like for me when I was a beginner.

Leave a Comment