Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we see Arity related exceptions at runtime in Clojure?

Tags:

clojure

Why do we see Arity related exceptions at runtime in Clojure?

I suppose, this is something that a compiler should be able to check when we compile the code itself. What is the reason that we only catch such errors at runtime. ?

like image 991
Amogh Talpallikar Avatar asked Oct 18 '25 13:10

Amogh Talpallikar


2 Answers

Clojure's compile-time type information is pretty limited. Functions like map have no way to specify that it only accepts one-argument functions (and of course that's not even really true, with multi-collection map calls). Likewise, apply makes everything really really complicated: consider (apply f (read-list-from-user)). Does that compile successfully? Of course it must, even though we don't know if the user will enter the right number of args for f. Thus, there has to be a runtime exception for that case; then you might as well make all arity exceptions runtime anyway, since you can't be protected from them by the compiler.

like image 96
amalloy Avatar answered Oct 21 '25 02:10

amalloy


In Clojure, at compile-time phase; the data structures that are previously generated by the reader are converted to Java bytecode format. Then at Clojure runtime phase; the bytecode is executed. This means that functions are only invoked at runtime.

Of course, Macros expansion happens at compile time phase.

I think, that is why exceptions related to functions arities are caught at runtime phase.

like image 40
Chiron Avatar answered Oct 21 '25 03:10

Chiron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!