1

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 ?

3
  • Yes. And it would take 15 minutes to try and see this yourself, including some reading if necessary. Commented Jan 27, 2016 at 9:12
  • @muhukI assumed there were differences, since protocols are faster than cond for instance. " it would take 15 minutes to try and see this yourself, including some reading if necessary." => I am doing it right now :) Commented Jan 27, 2016 at 9:24
  • 2
    To avoid misunderstandings: I didn't mean 15 mins thing in a RTFM sense. But it is generally a good idea to try things out and post your results and sometimes it can result in a different, better described question. Also, I am assuming you are aware of recur. Commented Jan 27, 2016 at 9:36

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.