让Vars在多个文件中正确绑定

时间:2010-03-20 03:48:26

标签: clojure

我正在学习Clojure,并且无法将代码移动到不同的文件中。

我继续将此错误从appnrunner.clj -

中删除
Exception in thread "main" java.lang.Exception: Unable to resolve symbol: -run-application in this context

似乎找到了名称空间很好,但后来却没有看到Vars被绑定......不知道如何解决这个问题吗?

这是我的代码:

APPLICATION RUNNER -

(ns src/apprunner
  (:use src/functions))

(def input-files [(resource-path "a.txt") (resource-path "b.txt") (resource-path "c.txt")])
(def output-file (resource-path "output.txt"))

(defn run-application []
  (sort-files input-files output-file))

(run-application)

申请职能 -

(ns src/functions
  (:use clojure.contrib.duck-streams))

(defn flatten [x]
  (let [s? #(instance? clojure.lang.Sequential %)]
    (filter
      (complement s?)
      (tree-seq s? seq x))))

(defn resource-path [file]
  (str "C:/Users/Alex and Paula/Documents/SoftwareProjects/MyClojureApp/resources/" file))

(defn split2 [str delim]
  (seq (.split str delim)))

(defstruct person :first-name :last-name)

(defn read-file-content [file]
  (apply str
    (interpose "\n" (read-lines file))))

(defn person-from-line [line]
  (let [sections (split2 line " ")]
    (struct person (first sections) (second sections))))

(defn formatted-for-display [person]
  (str (:first-name person) (.toUpperCase " ") (:last-name person)))

(defn sort-by-keys [struct-map keys]
  (sort-by #(vec (map % [keys])) struct-map))

(defn formatted-output [persons output-number]
  (let [heading (str "Output #" output-number "\n")
        sorted-persons-for-output (apply str (interpose "\n" (map formatted-for-display (sort-by-keys persons (:first-name :last-name)))))]
    (str heading sorted-persons-for-output)))

(defn read-persons-from [file]
  (let [lines (read-lines file)]
    (map person-from-line lines)))

(defn write-persons-to [file persons]
  (dotimes [i 3]
    (append-spit file (formatted-output persons (+ 1 i)))))

(defn sort-files [input-files output-file]
  (let [persons (flatten (map read-persons-from input-files))]
    (write-persons-to output-file persons)))

1 个答案:

答案 0 :(得分:4)

您没有正确命名您的命名空间!

你应该做这样的事情:


;;; in file src/apprunner/core.clj
;;; (namespace names should contain at least one dot for things
;;; not to go into the default package... or some such thing)
(ns apprunner.core
  (:use apprunner.functions)

;;; the rest of your code for this file follows unchanged

;;; in file src/apprunner/functions.clj
(ns apprunner.functions
  (:use clojure.contrib.duck-streams))

;;; the rest of your code for this file follows unchanged

在REPL((use 'apprunner.core)等)运行上述内容对我来说很好。

总结一下这里的问题:名称空间名称应包含点,其中定义文件的路径包含斜杠/反斜杠(不是指我的意思是相对路径 - 相对于实际上的某个目录classpath)。此外,src/目录是您放在类路径中的目录,因此您不在命名空间名称中包含src.部分。参见例如我对your earlier question的回答中的src/foo/bar/baz.cljfoo.bar.baz示例。

哦,顺便说一下,弄清楚类路径很困难的时期。所以,一定不要让自己因这类问题而气馁! :-)如果你有更多的命名空间或类路径相关的问题,或者如果上面的问题没有解决你的问题,你可能想要包含有关如何运行代码的信息。