instance? with one argument

66 views
Skip to first unread message

Phillip Lord

unread,
Feb 27, 2013, 12:01:30 PM2/27/13
to clo...@googlegroups.com


The instance? function does not crash with a single argument, when I
think that it should throw an arity exception.

I asked on SO about this a while back, so I now know why, but I got hit
by this again yesterday. I think this is a bug, but I am not sure
whether I have missed a good reason why it is not considered so.


http://stackoverflow.com/questions/13176400/clojure-instance-single-argument

Herwig Hochleitner

unread,
Feb 27, 2013, 1:59:35 PM2/27/13
to clo...@googlegroups.com
This special handling technique is known as a compiler macro in clojurescript (and elsewhere). Essentially, all direct calls to instance? get emitted as an instanceof expression for performance.
Higher order uses behave as expected:

user=> (apply instance? Long [])
ArityException Wrong number of args (1) passed to: core$instance-QMARK-  clojure.lang.AFn.throwArity (AFn.java:437)

Unfortunately the handler in the compiler doesn't do arity checks, hence the behavior you see. IMO this is a bug. 
I can't speak for clojure/core, but I believe ticket and patch would be welcome in this case.

Herwig Hochleitner

unread,
Feb 27, 2013, 2:22:14 PM2/27/13
to clo...@googlegroups.com
Also direct calls are only handled, if the first arg is a symbol that directly resolves to a class:

user=> (def C Long)
user=> (instance? C)
ArityException Wrong number of args (1) passed to: core$instance-QMARK-  clojure.lang.AFn.throwArity (AFn.java:437)

Starting from this, I just discovered another, much more severe bug:

user=> (let [Long String] (instance? Long "abc"))
false


Phillip Lord

unread,
Feb 28, 2013, 4:44:17 AM2/28/13
to clo...@googlegroups.com

Yes, you are right about the lexical binding; I suspect that is less
likely to hit people though. I don't know why I keep typing

(instance? String)

but I've done it a lot. Possibly because I am using a Java API with a
lot of very similar classes; by the time I have managed to find out
which class I need to check, I've forgotten what I was doing in the
first place.

Thanks for opening the ticket!
> --

--
Phillip Lord, Phone: +44 (0) 191 222 7827
Lecturer in Bioinformatics, Email: philli...@newcastle.ac.uk
School of Computing Science, http://homepages.cs.ncl.ac.uk/phillip.lord
Room 914 Claremont Tower, skype: russet_apples
Newcastle University, twitter: phillord
NE1 7RU
Reply all
Reply to author
Forward
0 new messages