Reputation: 18005
In order to better understand Clojure protocols, I am asking myself if they act exactly like a cond
. For instance this function may overflow :
(defn my-cond [n]
(cond
(< n 0) (my-cond (inc n))
(> n 0) (my-cond (dec n))
:else "zero"))
> (my-cond 3) ;; "zero" > (my-cond 99999999) ;; java.lang.StackOverflowError
For instance, let's say I now use a protocol to make an equivalent (ie. recursive protocol call). Does it change in any way the way the stack could blow ?
My intuition says no (how could it be), but (1) I have no understanding of the protocol internals and (2) since they make the code less coupled, it probably makes it easier to introduce this kind of loop and so it would make sense to be able to prevent it.
Do protocols and multimethods use the stack in the same way as normal method calls ?
Upvotes: 1
Views: 145
Reputation: 10672
Yes; Functions, methods, multimethods and protocols all push their context onto the stack. However protocols differ from a function call with a conditional or a multimethod because a protocol exposes single dispatch on type, and the JVM is very fast at that. Also types make protocols usable from Java in ways that a dynamic function is not. So yes they are semantically the same thing, but they also fulfill a practical need of speed and interop with the underlying platform.
Upvotes: 3