Two functions that recursively call each other

Is it possible to define two functions in clojure that call each other recursively? For example, this pair:

(defn a [x] (if (= 0 x) 0 (b (dec x)))) (defn b [x] (if (= 0 x) 0 (a (dec x)))) 

Fail compilation:

 Unable to resolve symbol: b in this context 

Since I did not define b when I try to call it in a .

for example, in ruby ​​this works fine:

 def a(x) x == 0 ? x : b(x-1) end def b(x) x == 0 ? x : a(x-1) end 
+6
source share
2 answers

or:

(declare b) ...; the rest of your code can be used as

or

 (def mutual (letfn [(a [ ... ] ...) (b [ ... ] ...)] [ab])) (def a (first mutual)) (def b (second mutual)) 
+6
source

Depending on the execution of your code, keep in mind that you may get an exception.

Where the function (clojure.core / trampoline) comes into play and does its magic.

trampoline can be used to convert algorithms requiring mutual recursion without consuming a stack. Calls f with the arguments provided, if Any. If f returns fn, calls fn with no arguments, and continues to repeat until the return value is fn, then this non-fn value returns. Note that if you want to return fn as a final value, you must wrap it in some data structure and unpack it after the trampoline returns.

+6
source

Source: https://habr.com/ru/post/952430/


All Articles