defrecord类未找到例外

时间:2014-11-03 08:56:05

标签: clojure

我有两个文件knapsack.cljcore.clj

defrecord Item中有knapsack.clj。我想在core.clj中使用它,但它在cider-repl的{​​{1}}中给出了错误,即使我java.lang.ClassNotFoundException: discrete-optimization.knapsack.Item命名空间有require

代码在这里:

knapsack

我的clojure版本为;; ---- knapsack.clj --------- (ns discrete-optimization.knapsack) ;; Item record has weight and value of the Item (defrecord Item [weight value]) ;; ---- core.clj -------- (ns discrete-optimization.core (:require [discrete-optimization.knapsack :as KS]) (:import [discrete-optimization.knapsack Item])) ;; doing some knapsack in here.. :) (and (= 5 (KS/knapsack-value 5 [(Item. 3 5)])) (= 5 (KS/knapsack-value 5 [(Item. 3 3) (Item. 2 2)])))

解决方案: 对于便携式解决方案:

在引用名称空间外的1.5.1时使用->KS/item

2 个答案:

答案 0 :(得分:3)

虽然xsc的答案没有错,但我的偏好是使用从defrecord生成的构造函数,并避免使用Java构造函数和Java import -isms。随着时间/平台的发展,这可能更具可移植性。

;; ---- knapsack.clj ---------
(ns discrete-optimization.knapsack)
;; Item record has weight and value of the Item
(defrecord Item      
    [weight value])  
;; The ->Item constructor is generated automatically

;; ---- core.clj --------
(ns discrete-optimization.core
  (:require [discrete-optimization.knapsack :as KS]))

;; doing some knapsack in here.. :)
(and 
 (= 5 (KS/knapsack-value 5 [(KS/->Item 3 5)]))
 (= 5 (KS/knapsack-value 5 [(KS/->Item 3 3) (KS/->Item 2 2)])))

答案 1 :(得分:2)

:import引用Java类 - 当为Clojure编译器创建包/类名时,将破折号转换为下划线。这可能因此起作用:

(:import [discrete_optimization.knapsack Item])