Peter Groves
Peter Groves

Reputation: 411

How do you find the record type of an input in Clojure?

I can't figure out how to do something like (instance? MyRecordType x) when MyRecordType was declared using defrecord. The type and class of the records are always clojure.lang.PersistentArrayMap.

For instance:

(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

Upvotes: 1

Views: 937

Answers (1)

maxthoursie
maxthoursie

Reputation: 471

It should work that way. This is what your example looks like on 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

Upvotes: 1

Related Questions