(defrecord Point [x y])
;; 协议可以附加到自己没有源码的类型上,
;; 这就是 Clojure 的“扩展方法”
(defprotocol Distance
(distance-to [this other]))
(extend-protocol Distance
Point
(distance-to [p other]
(Math/hypot (- (:x p) (:x other))
(- (:y p) (:y other)))))
(def distance (distance-to (->Point 1.0 2.0) (->Point 2.0 3.0)))
;; distance is 1.4142
(println "distance is" (format "%.4f" distance))
;; 同样的做法也适用于 Java 类,包括 String
(extend-protocol Distance
String
(distance-to [s other] (abs (- (count s) (count other)))))
(println "distance is" (distance-to "abcde" "ab"))