Newbie question: testing if an object is a Struct of a certain kind

129 views
Skip to first unread message

samppi

unread,
Oct 29, 2008, 2:29:09 PM10/29/08
to Clojure
Is there a way to test an object if it's a certain kind of struct?

(defstruct person :name :age)
(def president (struct person "Sam" 30))
(struct? person president) ; true

Thanks in advance.

Graham Fawcett

unread,
Oct 29, 2008, 3:01:59 PM10/29/08
to clo...@googlegroups.com
On Wed, Oct 29, 2008 at 2:29 PM, samppi <rbys...@gmail.com> wrote:
>
> Is there a way to test an object if it's a certain kind of struct?
>
> (defstruct person :name :age)
> (def president (struct person "Sam" 30))
> (struct? person president) ; true

Hi,

Defstruct doesn't define a new type in the OO sense. You can test for
presence of keys, e.g.

(every? #{:name :age} (keys president))

will return true, because 'president' has both :name and :age keys.
But other structures might also have these keys, so this is "duck
typing" at best.

Others have suggested using metadata to "tag" struct values with type
information -- that might be an option you prefer over
key-comparision.

Best,
Graham

>
> Thanks in advance.
>
>
> >
>

samppi

unread,
Oct 29, 2008, 3:27:42 PM10/29/08
to Clojure
Okay, I understand. Thanks for the answer.

On Oct 29, 12:01 pm, "Graham Fawcett" <graham.fawc...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages