我从面向对象程序员的函数编程一书中得到了这个clojure代码:
(def point {:x 1, :y 2, :__class_symbol__ 'Point})
(def Point
(fn [x y]
{:x x,
:y y
:__class_symbol__ 'Point}))
(def x :x)
(def y :y)
(def class-of :__class_symbol__)
(def shift
(fn [this xinc yinc]
(Point (+ (x this) xinc)
(+ (y this) yinc))))
(defn add [left right]
(shift left (x right) (y right)))
(def Triangle
(fn [point1 point2 point3]
{:point1 point1, :point2 point2, :point3 point3
:__class_symbol__ 'Triangle}))
(def right-triangle (Triangle (Point 0 0)
(Point 0 1)
(Point 1 0)))
(def equal-right-triangle (Triangle (Point 0 0)
(Point 0 1)
(Point 1 0)))
(def different-triangle (Triangle (Point 0 0)
(Point 0 10)
(Point 10 0)))
(defn equal-triangles? [& args]
(apply = args))
(defn make [klass & args]
(apply klass args))
我创建了这个函数来检查Triangle伪类的相等性:
(defn equal-triangles? [& args]
(apply = args))
很明显为什么这个表达式是真的
(= right-triangle right-triangle)
为什么这个表达式不正确也很明显
(equal-triangles? right-triangle different-triangle)
不明显的是为什么这个表达式为真:
(= right-triangle equal-right-triangle)
他们都有Point值,但我认为他们会有所不同,因为我可能仍在考虑实例。
任何人都可以解释为什么最后一个表达式是真的吗?
答案 0 :(得分:2)
user=> (= right-triangle equal-right-triangle)
true
user=> (identical? right-triangle equal-right-triangle)
false
user=> (doc =) ------------------------- ... Clojure's immutable data structures define equals() (and thus =) as a value, not an identity, comparison. user=> (doc identical?) ------------------------- ...Tests if 2 arguments are the same object