可以在Clojure 1.4.0中扩展与defrecord一起使用吗?

时间:2013-01-12 22:37:11

标签: clojure

我正在尝试使用'extend'来定义带有Clojure中地图的记录方法。以下适用于Clojure 1.4.0:

(defprotocol PointMethods
  (add [self other])
  (distance [self]))

(defrecord Point [x y]
  PointMethods
  (add [self other]
    (Point. (+ (:x self) (:x other)) (+ (:y self) (:y other))))
  (distance [self]
    (Math/sqrt (+ (* (:x self) (:x self)) (* (:y self) (:y self))))))

(def p1 (Point. 2 3))
(def p2 (Point. 1 1))

(def p3 (add p1 p2))
(println p3)
(println (distance p3))

但是这个版本失败了:

(defprotocol PointMethods
  (add [self other])
  (distance [self]))

(defrecord Point [x y])
(extend Point
  PointMethods
  {:add
   (fn [self other] (Point. (+ (:x self) (:x other)) (+ (:y self) (:y other))))
   :distance
   (fn [self] (Math/sqrt (+ (* (:x self) (:x self)) (* (:y self) (:y self)))))})

(def p1 (Point. 2 3))
(def p2 (Point. 1 1))

(def p3 (add p1 p2))
(println p3)
(println (distance p3))

Clojure Compiler: java.lang.IllegalArgumentException: No implementation of method: :add 
of protocol: #'user/PointMethods found for class: user.Point, compiling:(records.clj:16)]

第二个版本有什么问题?

1 个答案:

答案 0 :(得分:0)

正如其他人在他们对您的代码的评论中所指出的那样,您编写的代码在Clojure 1.4.0中运行良好(我只是自己验证了)。您可能遇到某种IDE配置错误,或者可能存在一些陈旧的缓存字节码。