【问题标题】:IllegalArgumentException: No implementation of method: :as-file of protocol: #'clojure.java.io/Coercions found for class: clojure.lang.SymbolIllegalArgumentException:没有方法的实现::协议文件:#'clojure.java.io/Coercions 为类找到:clojure.lang.Symbol
【发布时间】:2021-08-30 22:17:39
【问题描述】:

我正在尝试编写一个宏,以便从 ClojureScript 中使用来处理 Reagent 应用程序的文件 I/O。我收到此错误:

IllegalArgumentException: No implementation of method: :as-file of protocol: #'clojure.java.io/Coercions found for class: clojure.lang.Symbol

当我尝试执行以下操作时:

(def file-string "/Users/luciano/Dropbox/projects/test/resources/blog/test.md")
(get-file file-string)

但我可以做到这一点:

(get-file "/Users/luciano/Dropbox/projects/test/resources/blog/test.md")

这是宏:

(defmacro get-file [fname]
  (slurp (io/file fname)))

我在这里做错了什么?

【问题讨论】:

    标签: clojure clojurescript


    【解决方案1】:

    这意味着您尝试使用在运行时没有值的符号调用宏。

    (def my-file "foo.txt")
    (def file-str (get-file my-file))
    

    将工作,而

    (defn foo [s]
      (get-file s))
    
    (foo "foo.txt")
    

    不会。

    【讨论】:

    • 就是这个原因!谢谢
    • 这个答案不正确! get-file 是一个宏。宏操作文字(并返回 ClojureScript 形式以代替宏使用)。这个在字符串文字上调用的 get-file 宏可以使用字符串并因此读取指示的文件(在构建机器上,在编译时);但是如果在一个符号上调用,那么这个符号就是它所接收的。编译器在将宏的参数交给宏之前不会处理它们。如果您真的想这样做,请查看 resolve 函数,了解宏可能对符号执行的操作。
    【解决方案2】:

    您不应该为此使用宏。

    宏最好被视为嵌入在源代码中的编译器扩展。

    您只需要一个常规函数,例如:

    (defn get-file 
      [fname]
      (slurp (io/file fname)))
    

    就从 Reagent 应用程序执行 I/O 而言,我不确定您的目标是什么。

    【讨论】:

    • 我认为目标是在编译时静态提取一些资源并将数据嵌入到生成的 cljs 中。
    猜你喜欢
    • 1970-01-01
    • 2021-10-06
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多