Search code examples
functionclojurecyclic-dependency

Are clojure function cyclic dependencies specifically disallowed by design, or is it just a reader behaviour?


If I do the following in clojure

(defn sub1a [a]
  (cond
    (= a 0) 0
    true (sub1b (- a 1) )))

(defn sub1b [a]
  (cond
    (= a 0) 0
    true (sub1a (- a 1) )))

(println (sub1a 10))

I get the following error:

java.lang.Exception: Unable to resolve symbol: sub1b in this context

But if I do the following:

(defn sub1a [a]
  (cond
    (= a 0) 0
    true (- a 1)))

(defn sub1b [a]
  (cond
    (= a 0) 0
    true (- a 1)))

(defn sub1a [a]
  (cond
    (= a 0) 0
    true (sub1b (- a 1) )))

(defn sub1b [a]
  (cond
    (= a 0) 0
    true (sub1a (- a 1) )))

(println (sub1a 10))

It runs just fine.

Is this by design, or just a function of the way the Clojure reader works?


Solution

  • You can do

    (declare sub1a sub1b)
    

    'declare' is specifically meant to create a var with no bindings for making forward declarations.

    One you declared the names:

    (defn sub1a [a]
      (cond
        (= a 0) 0
        true (sub1b (- a 1) )))
    
    (defn sub1b [a]
      (cond
        (= a 0) 0
        true (sub1a (- a 1) )))
    
    (println (sub1a 10))
    

    Also the idomatic way to specify the default condition in cond (for clojure) is using the :else clause. This is a bit different from Common Lisp which uses T (for True). So your previous code can be rewritten as:

    (defn sub1a [a]
      (cond
        (= a 0) 0
        :else (sub1b (- a 1) )))
    
    ...