【问题标题】:Special reader macros like [ ], { }特殊的阅读器宏,如 [ ]、{ }
【发布时间】:2013-06-12 10:15:47
【问题描述】:

我想写一些特殊的阅读器宏:

[hello "world"] ; <=> (funcall #'|hello| "world")
{hello "my" ("world")} ; <=> (apply #'|hello| "my" ("world"))

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

【问题讨论】:

    标签: lisp common-lisp


    【解决方案1】:

    是的,你要的词是readtableCommon Lisp HyperSpec chapter 23Common Lisp HyperSpec chapter 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)))))))
    

    之后,您需要将其连接到 readtable 并将一些语法标记从 () 复制到新的分隔符。

    【讨论】:

    • 我还建议使用 named-readtales 库,它可以让您编写不同的可读修改并帮助避免与其他人的修改混淆
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 2017-07-25
    • 2018-05-21
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多