【问题标题】:How do you find the record type of an input in Clojure?如何在 Clojure 中找到输入的记录类型?
【发布时间】:2013-10-28 22:56:12
【问题描述】:

当使用 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

【问题讨论】:

  • 您使用的是哪个版本的 Clojure?这对我有用...

标签: class types clojure record


【解决方案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

【讨论】:

  • 回到这个问题后,我无法再重现该问题。我知道我得到了原始问题所声称的某种形式,但这是我现在在干净的 repl 和单元测试中得到的。很抱歉产生噪音,因为它一定是用户错误,但我很欣赏额外的眼睛。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-02
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 1970-01-01
  • 2020-11-11
相关资源
最近更新 更多