Type Information

7 views
Skip to first unread message

Paul Drummond

unread,
Feb 29, 2008, 8:02:23 AM2/29/08
to Clojure
Hi,

I am new to Lisp. I have played around with CL and Scheme and read 50%
of PCL before taking a look at Clojure. So far I have just been
playing around in the REPL and I've found I am missing the ability to
query for the type of a symbol like I can in Python for example:

Python:
>>> a = {"a":2}
>>> type(a)
<type 'dict'>

Is there a way to do this in Clojure?

Cheers,
Paul Drummond



Rich Hickey

unread,
Feb 29, 2008, 8:24:19 AM2/29/08
to Clojure


On Feb 29, 8:02 am, Paul Drummond
As in Python/CL/Scheme, in Clojure the object has a type, not the
symbol/variable. Clojure doesn't have a type system independent of
Java's, so the normal Java method applies:

(. a (getClass))

There isn't yet a Clojure function that makes this shorter, and
surprisingly no one has asked for one (or has everyone rolled their
own?)

As always in a system with inheritance, it can be dangerous to rely on
the concrete types of things:

user=> (def a {"a" 2})
user=> (. a (getClass))
class clojure.lang.MapEntry

user=> (def ab {"a" 2 "b" 3})
user=> (. ab (getClass))
class clojure.lang.PersistentHashMap

Whereas testing whether something implements a specific interface is
generally more useful:

user=> (map? a)
true
user=> (map? ab)
true

where (map? x) is a helper function defined as (instance?
IPersistentMap x). There are similar helpers for symbol?, vector?,
seq? string? etc.

Rich

Paul Drummond

unread,
Feb 29, 2008, 8:51:22 AM2/29/08
to Clojure
Wow, you respond quickly - thanks!

> As in Python/CL/Scheme, in Clojure the object has a type, not the
> symbol/variable. Clojure doesn't have a type system independent of
> Java's, so the normal Java method applies:
>
> (. a (getClass))

Ahhhh, I see. Why didn't I think of that?!

> There isn't yet a Clojure function that makes this shorter, and
> surprisingly no one has asked for one (or has everyone rolled their
> own?)

So:

(defn type [o] (. o (getClass)))

is what I need. Cool.

> As always in a system with inheritance, it can be dangerous to rely on
> the concrete types of things

Yep, I think the use of the type() function as in Python is really
helpful when experimenting/exploring at the REPL rather than for use
in real code.

For that reason alone, could I request the addition of a type function
in boot.clj please? I ask because I am thinking of writing a tutorial
(eventually) and having a type function as standard would be really
helpful for explaining how things work.

Cheers,
Paul.

Rich Hickey

unread,
Feb 29, 2008, 9:23:28 AM2/29/08
to Clojure


On Feb 29, 8:51 am, Paul Drummond
Ok. It's called class:

user=> (class "foo")
class java.lang.String

Rich

Paul Drummond

unread,
Feb 29, 2008, 9:31:02 AM2/29/08
to Clojure
Excellent, thank you!
Reply all
Reply to author
Forward
0 new messages