The less-familiar parts of Lisp for beginners — set-syntax-from-char

The function set-syntax-from-char allows the programmer to copy a read-macro from one character in a particular readtable and duplicate it on possibly a different character in another readtable.  To understand what this means, you may want to review the earlier discussion of readtables.

Here is an example.  It’s not something I would recommend doing in real code, it’s just here for demonstration purposes.  If I want to write some code which contains a lot of strings with embedded double-quote marks, I might be tempted to come up with a new string delimiter to use in that case.  In this code, I copy the meaning of ” into the underscore.  I can then write my code using double-quotes in some places, and underscores in others.  A string that begins with an underscore can only be ended with another underscore, not the double-quote, so this allows me to embed double-quote characters easily in a string.

Naturally, this novel string syntax would break at load time, so we have to use eval-when to modify the readtable before forms using this syntax are read.  Also, note that the colorization is wrong in the code, because SLIME doesn’t know about this new string format, and thinks that I have an unterminated string in my code.  Here’s the code:
set-syntax-from-char.lisp

(eval-when (:compile-toplevel :load-toplevel :execute)
  (set-syntax-from-char #\_ #\"))

(defun demonstrate ()
  (format t "Here is a string: ~S~%" "abcd")
  (format t "Here is another string: ~S~%" _ab"cd_))

Producing the output:
*slime-repl sbcl*
CL-USER> (demonstrate)
Here is a string: "abcd"
Here is another string: "ab\"cd"
NIL

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

*

反垃圾邮件 / Anti-spam question * Time limit is exhausted. Please reload CAPTCHA.