【问题标题】:Can you get the "code as data" of a loaded function in Clojure?你能在 Clojure 中获取加载函数的“代码即数据”吗?
【发布时间】:2012-03-02 08:09:14
【问题描述】:

换句话说,“Okay, so code is data...”

该线程解决了如何从源文件中读取数据,但我想知道如何将已加载函数的 s 表达式转换为我可以读取和操作的数据结构。

换句话说,如果我说,

(defn example [a b] (+ a b))

我不能在运行时获得该列表吗?这不就是“代码即数据”的全部意义所在吗?

这确实是一个通用的 Lisp 问题,但我正在 Clojure 中寻找答案。

【问题讨论】:

    标签: reflection clojure


    【解决方案1】:

    您可以使用clojure.repl/source 宏来获取符号的来源:

    user> (source max)
    (defn max
      "Returns the greatest of the nums."
      {:added "1.0"
       :inline-arities >1?
       :inline (nary-inline 'max)}
      ([x] x)
      ([x y] (. clojure.lang.Numbers (max x y)))
      ([x y & more]
       (reduce1 max (max x y) more)))
    nil
    

    但这只是答案的一部分。 AFAICT source 查找定义给定符号的源文件名和行号,然后从文件中打印源代码。因此,source 不适用于您没有源代码的符号,即 AOT 编译的 clojure 代码。

    回到您最初的问题,您可以将source 视为读取与给定符号关联的元数据并简单地打印它。 IE。这是作弊。它绝不会以任何方式将“代码作为数据”返回给您,这里的代码是指已编译的 clojure 函数。

    在我看来,“代码即数据”指的是 lisp 的特性,其中源代码实际上是一种 lisp 数据结构,因此它可以被 lisp 阅读器读取。也就是说,我可以创建一个有效的 lisp 代码的数据结构,以及eval。

    例如:

    user=> (eval '(+ 1 1))
    2
    

    这里的'(+ 1 1) 是一个文字列表,它被 clojure 阅读器读取,然后作为 clojure 代码进行评估。

    更新: Yehonathan Sharvit 在其中一个 cmets 中询问是否可以修改函数的代码。下面的 sn-p 读入一个函数的源代码,修改生成的数据结构,最后评估数据结构,从而定义一个新函数 my-nth:

    (eval
     (let [src (read-string (str (source-fn 'clojure.core/nth) "\n"))]
       `(~(first src) my-nth ~@(nnext src))))
    

    syntax-quote 行将nth 替换为defn 表单中的my-nth。

    【讨论】:

    • 这个 sn-p 让我开始了我感兴趣的道路,但我相信真正的答案是,不,Clojure 不会在内部保留函数的“数据”表示。例如,此方法在动态创建的函数上不起作用,并且正如您所指出的,在源代码消失后甚至在预编译的函数上也不可用。为了得到我想要的东西,你似乎需要使用一个特殊的表单记录宏来定义函数,正如this discussion 中所建议的那样。感谢您的帮助。
    • 如果我这样做:(def x {:add-ten #(+ % 10)}),那么 (:add-ten x) 的代码存储在哪里?它是否存储为字节码?
    【解决方案2】:

    您可以使用 source 函数在最新版本的 clojure 中获取源代码。

    user=> (source nth)
    (defn nth
      "Returns the value at the index. get returns nil if index out of
      bounds, nth throws an exception unless not-found is supplied.  nth
      also works for strings, Java arrays, regex Matchers and Lists, and,
      in O(n) time, for sequences."
      {:inline (fn  [c i & nf] `(. clojure.lang.RT (nth ~c ~i ~@nf)))
       :inline-arities #{2 3}
       :added "1.0"}
      ([coll index] (. clojure.lang.RT (nth coll index)))
      ([coll index not-found] (. clojure.lang.RT (nth coll index not-found))))
    nil
    

    要获取字符串作为值,您可以将其包装在with-out-str:

    user=> (with-out-str (source nth))
    "(defn nth\n  \"Returns the value at the index. get returns nil if index out of\n  bounds, nth throws an exception unless not-found is supplied.  nth\n  also works for strings, Java arrays, regex Matchers and Lists, and,\n  in O(n) time, for sequences.\"\n  {:inline (fn  [c i & nf] `(. clojure.lang.RT (nth ~c ~i ~@nf)))\n   :inline-arities #{2 3}\n   :added \"1.0\"}\n  ([coll index] (. clojure.lang.RT (nth coll index)))\n  ([coll index not-found] (. clojure.lang.RT (nth coll index not-found))))\n"
    user=> 
    

    【讨论】:

    • 谢谢,这本身就很有帮助。但这只是将源打印到标准输出,而不是返回值(正如我从运行 (source source) 中看到的那样)。再一次,也许我只是不理解 Lisp 和函数式的整个想法。为什么没有一个函数来return这些信息,并以结构化的形式返回?
    • 编辑修复。你不需要一个单独的函数来返回它,因为你可以用with-out-str
    • 有没有办法修改函数的源代码?
    • @YehonathanSharvit:您可以使用source-fn 生成函数的字符串表示,然后使用一些Java 流胶,read 将它返回到Clojure 列表。之后,您可以根据自己的心愿随意操纵 Clojure 列表,最后eval 它。
    • @ArthurUlfeldt:您可以调用(source-fn 'nth) 而不是(with-out-str (source nth)) 以获得相同的效果。
    【解决方案3】:

    那是我的信息;很高兴见到你;-) 顺便说一句,该线程中给出的答案参考资料非常好;因此,如果您有兴趣,可能需要花时间阅读它们。回到您的问题,尽管source 似乎适用于通过文件加载的代码,但并非在所有情况下都有效。我认为,具体来说,它不适用于 repl 中定义的函数。

    user=> (def foo (fn [] (+ 2 2)))
    #'user/foo
    user=> (source foo)
    Source not found
    nil
    user=> (defn foo2 [] (+ 2 2))
    #'user/foo2
    user=> (source foo2)
    Source not found
    nil
    

    挖一点……

    user=> (source source)
    (defmacro source
      "Prints the source code for the given symbol, if it can find it.
      This requires that the symbol resolve to a Var defined in a
      namespace for which the .clj is in the classpath.
    
      Example: (source filter)"
      [n]
      `(println (or (source-fn '~n) (str "Source not found"))))
    nil
    user=> (source clojure.repl/source-fn)
    (defn source-fn
      "Returns a string of the source code for the given symbol, if it can
      find it.  This requires that the symbol resolve to a Var defined in
      a namespace for which the .clj is in the classpath.  Returns nil if
      it can't find the source.  For most REPL usage, 'source' is more
      convenient.
    
      Example: (source-fn 'filter)"
      [x]
      (when-let [v (resolve x)]
        (when-let [filepath (:file (meta v))]
          (when-let [strm (.getResourceAsStream (RT/baseLoader) filepath)]
            (with-open [rdr (LineNumberReader. (InputStreamReader. strm))]
              (dotimes [_ (dec (:line (meta v)))] (.readLine rdr))
              (let [text (StringBuilder.)
                    pbr (proxy [PushbackReader] [rdr]
                          (read [] (let [i (proxy-super read)]
                                     (.append text (char i))
                                     i)))]
                (read (PushbackReader. pbr))
                (str text)))))))
    nil
    

    是的,看起来它试图从类路径中加载源文件以尝试为您吐出它。我在使用 Clojure 时学到的一件事是,十分之九的时候查看源代码很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-30
      • 2010-09-28
      • 2021-10-31
      • 1970-01-01
      • 2021-02-21
      • 2010-10-10
      相关资源
      最近更新 更多