像[],{}这样的特殊读者宏

Mik*_*one 1 lisp common-lisp

我想写一些特殊的读者宏:

[hello "world"] ; <=> (funcall #'|hello| "world")
{hello "my" ("world")} ; <=> (apply #'|hello| "my" ("world"))
Run Code Online (Sandbox Code Playgroud)

这可以实施吗?你会怎么做?

Vat*_*ine 6

是的,你是想术语是readtable(Common Lisp的HyperSpec章23Common Lisp的HyperSpec第2章谈的相关概念).

您需要先定义一个可以读取您感兴趣的数据的函数,然后以您想要的形式返回它.

(defun read-case-preserve-funcall-or-apply (stream char)
  (let ((preserved-readtable-case (readtable-case *readtable*)))
    (setf (readtable-case *readtable* :preserve))
    (let ((tmp (read-delimited-list (if (char= char #\[) #\] #\}) stream t)))
      (let ((fun (car tmp))
        (args (cdr tmp)))
    (cond ((char= char #\[) `(funcall (function ,fun) ,@args))
          ((char= char #\{) `(apply (function ,fun) ,@args)))))))
Run Code Online (Sandbox Code Playgroud)

在此之后,你需要把它挂到readtable和复制一些语法标记(,并)到新的分隔符.

  • 我还建议使用[named-readtales](http://common-lisp.net/project/named-readtables/)库来完成它,这将允许您编写不同的可读修改并帮助避免与其他人混在一起人民的 (2认同)