1

当使用 defrecord 声明 MyRecordType 时,我无法弄清楚如何执行类似 (instance?MyRecordType x) 之类的操作。记录的类型和类始终是 clojure.lang.PersistentArrayMap。

例如:

(defrecord MyRecord1 [data-field1 data-field2])
(defrecord MyRecord2 [data-field1])
(def x (->MyRecord1 1 2))
(def y (->MyRecord2 3))
(instance? MyRecord1 x)
 => false
(instance? MyRecord2 y)
 => false
(type x)
 => clojure.lang.IPersistentMap
(class y)
 => clojure.lang.IPersistentMap
(= (type x) (type y))
 => true
4

1 回答 1

1

它应该这样工作。这就是您的示例在 Clojure 1.5.1 上的样子

user=> (defrecord MyRecord1 [data-field1 data-field2])
user=> (defrecord MyRecord2 [data-field1])
user=> (def x (->MyRecord1 1 2))
user=> (def y (->MyRecord2 3))
user=> (instance? MyRecord1 x)
true
user=> (instance? MyRecord2 y)
true
user=> (type x)
user.MyRecord1
user=> (class y)
user.MyRecord2
user=> (= (type x) (type y))
false
于 2013-10-29T14:35:27.980 回答