在Clojure中定义我自己的阅读器宏
问题描述:
我想在clojure中定义自己的阅读器宏:
I would like to define my own reader macro in clojure:
(read-string "ßfoo")
=> (some_func :foo)
有可能吗?
答
可以通过在类路径顶部的 data_readers.clj
中具有阅读器映射来创建带标记的文字。
It is possible to create tagged literals by having a reader map in data_readers.clj
at the top of your classpath.
这必须位于类路径顶部的 data_readers.clj
中(通常为 src
目录)。
This must be in data_readers.clj
at the top of your classpath (usually src
directory).
{ß reader-demo.core/read-fn}
这进入到reader-demo.core
This goes into reader-demo.core
(defn some-func
[arg]
(str "some-func invoked with " arg))
(defn read-fn
[arg]
(-> arg
keyword
some-func))
调用
#ß foo
将返回
"some-func invoked with :foo"
此技术的描述如下:读者:带标记的文字
请注意,在实践中,应将带标记的文字命名为全部名称空间非命名空间保留给Clojure本身。
Notice that in practice you should namespace your tagged literals as all non-namespaced ones are reserved for Clojure itself.