Sunday, May 7

Python style tuples in Lisp

It's easy to extend Lisp to handle python-style tuples. This is all it takes:

(defun |#{-reader| (stream char arg)
(declare (ignore char arg))
`(values ,@(read-delimited-list #\} stream t)))

(set-dispatch-macro-character #\# #\{ #'|#{-reader|)
(set-macro-character #\} (get-macro-character #\) nil))

It installs a despatching macro in the readtable - so that when the reader encounters the #{ sequence it reads it up to the } terminating character, then splices it into a (values ...) form.

You can do neat things like (setf #{x y z} #{ 1.2 3.0 3.0 }) to do tuple assignment with no further work - it all falls out of the standard behaviour of Common Lisp.

What I'm wondering, now is if it's possible to combine readtable hacks with regular expressions to implement a lexical parser for an entirely different language without leaving Lisp. I guess it is, but I haven't got a project with a use for it. Yet.

1 comment:

Anonymous said...

(saw your recent post on reddit, browsing backwards)

you might want to look at xmlisp. they do things like (defvar *foo* <foo>hello world</foo>) using a dispatcher on <