Monday, June 28, 2004
Automaton cleanup
One of the nice things about posting code into your blog is there are a wealth of people on the 'net that will keep you honest. After posting my automaton code yesterday, Tim Moore wrote me with a style tip. Basically, Tim suggested I clean up the CONS/APPEND nightmare that existed in the innermost LOOP form. I had been thinking the same thing the night before when I did the post, so the suggestion was spot on. In particular, Tim said that his own personal rule is that when he sees lots of CONS/APPEND/LIST action, he takes it as a sign to replace the mess with a backquoted form.
Without further delay...
(defmacro define-automaton (name states &key (stop 'stop) (debug nil)) (let ((event-func (gensym "func"))) `(defun ,name (,event-func) (tagbody ,@(loop for (state-name . transitions) in states appending (list state-name `(case (funcall ,event-func) ,@(loop for (match next . actions) in transitions collecting `(,match ,@actions ,@(when debug `((format t "Matched ~A. Transitioning to state ~A.~%" ',match ',next))) (go ,next)))) `(go ,state-name))) ,stop))))
Ahhhh... much better.
Links to this post: