6

「拡張」を使用して、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)]

2 番目のバージョンの何が問題になっていますか?

4

1 に答える 1