Clojure:Lein run无法解析符号
我刚刚使用lein开始了我的第一个clojure项目,代码如下:Clojure:Lein run无法解析符号,clojure,Clojure,我刚刚使用lein开始了我的第一个clojure项目,代码如下: (ns fileops.core (:use [clojure.core :only (slurp)] [clojure-csv.core :only (parse-csv)] [fileops.core])) (defn -main "I don't do a whole lot ... yet." [& args] (read-file "sample.csv")) (def
(ns fileops.core
(:use
[clojure.core :only (slurp)]
[clojure-csv.core :only (parse-csv)]
[fileops.core]))
(defn -main
"I don't do a whole lot ... yet."
[& args]
(read-file "sample.csv"))
(defn read-file
"open and read the csv file"
[fname]
(with-open [file (clojure.java.io/reader fname)]
(parse-csv (slurp fname))))
我尝试使用“lein run”运行此操作,但不断出现以下错误:
Caused by: java.lang.RuntimeException: Unable to resolve symbol: read-file in this context
at clojure.lang.Util.runtimeException(Util.java:219)
at clojure.lang.Compiler.resolveIn(Compiler.java:6874)
at clojure.lang.Compiler.resolve(Compiler.java:6818)
at clojure.lang.Compiler.analyzeSymbol(Compiler.java:6779)
at clojure.lang.Compiler.analyze(Compiler.java:6343)
... 52 more
我做错了什么?您只使用了clojure core的slurp,这意味着您现在无法使用其他所有核心功能:)尝试将ns
更改为使用:require
,而不是:use
,因为这更为惯用
需要注意的一点是,在clojure中,顺序确实很重要,因此,如果不在文件顶部声明函数(如在C和其他一些语言中),早期的函数将无法引用它们。这就是之前导致错误的原因,也是我喜欢在底部定义我的-main
函数的原因。这是风格的问题
另一件事是,-main
函数现在正在接受变量arg,而不是使用它们。在Clojure中,习惯用法是使用\uu
引用未使用的参数。您可以使用&
来避免错误消息,例如当用户传入不必要的参数时,但我从一开始就将-main函数设为无参数。这是因为在运行程序时不需要向main提供任何内容,并且错误确实会使调试更容易。知道使用什么以及在哪里使用是很好的。已经提供了sample.csv
文件,并且正在调用该文件,因此如果read file
函数正确且sample.csv
文件位于正确位置,则程序应该运行
关于您的-main
函数,最好在其中放一个小测试,看看在您运行它时它是否正确执行,所以我更改了它,将csv文件的内容打印到您的控制台上。这种从文件打印的方法是有效的,值得单独研究
最后,确保在project.clj
文件中包含clojure csv.core
core.clj:
(ns fileops.core
(:require
[clojure-csv.core :refer [parse-csv]]))
(defn read-file
"open and read the csv file"
[fname]
(with-open [file (clojure.java.io/reader fname)]
(parse-csv (slurp fname))))
(defn -main []
(println (clojure.string/join "\n" (read-file "resources/test.csv"))))
project.clj:
...
:dependencies [[org.clojure/clojure "1.5.1"]
[clojure-csv/clojure-csv "2.0.1"]
...]
:main fileops.core
您需要将fileops.core声明为:main,如上所示。这告诉Leiningen当您输入lein run
时要执行什么函数。非常重要和棘手的事情
因此,现在请确保您位于项目目录的根目录中,并在终端运行以下操作:
lein clean
lein deps
lein run
祝你好运
进一步阅读:
在源代码中,读取文件应该在main之前,或者应该在-main之前声明原因,如下所示:
(declare read-file)
在你的源代码中,读取文件应该在main之前。@DiegoBasch你是个救生员。我是Clojure的新手,我花了太多时间试图弄清楚为什么在错误的上下文中调用我的函数会出错。就是这样。。。一直都是这样。棒极了。