Define my own reader macro in clojure

前端 未结 2 1742
借酒劲吻你
借酒劲吻你 2021-02-15 09:56

I would like to define my own reader macro in clojure:

(read-string \"ßfoo\")
=> (some_func :foo)

Is it possible?

2条回答
  •  臣服心动
    2021-02-15 10:47

    It is possible to create tagged literals by having a reader map in data_readers.clj at the top of your classpath.

    This must be in data_readers.clj at the top of your classpath (usually src directory).

    {ß reader-demo.core/read-fn}
    

    This goes into reader-demo.core

    (defn some-func
      [arg]
      (str "some-func invoked with " arg))
    
    (defn read-fn
      [arg]
      (-> arg
          keyword
          some-func))
    

    Invoking

    #ß foo
    

    will return

    "some-func invoked with :foo"
    

    This technique is described here: The reader: Tagged literals

    Notice that in practice you should namespace your tagged literals as all non-namespaced ones are reserved for Clojure itself.

提交回复
热议问题