Common function for self-triggering a recursive function in a definition

Is there a macro or basic reader function in Clojure that is similar to recur but possible with non-tail?

For example, in this recursive function

 (defn insertR* [newkey oldkey l] (cond (empty? l) '() (not (seq? (first l))) (if (= (first l) oldkey) (cons oldkey (cons newkey (insertR* newkey oldkey (rest l)))) (cons (first l) (insertR* newkey oldkey (rest l)))) :else (cons (insertR* newkey oldkey (first l)) (insertR* newkey oldkey (rest l))))) 

Is there some general function that I can use to call myself, and not to call insertR* explicitly?

+4
source share
2 answers

Your question is not clear. If you mean: can I do this without using stack space? No. Your insertR* has several independent calls, and this cannot be expressed without a stack.

If you mean: can I use a word like recur to mean "Call yourself recursively", and I don't care if it uses a stack? Not really. You could write it yourself. Sort of:

 (defmacro defrec [name & fntail] `(def ~name (fn ~'recurse ~@fntail ))) (defrec foo [x] (when-not (zero? x) (recurse (dec x)))) 

I suspect this one has a few holes, but basically this is what you are thinking about.

+3
source

Why do you need this function / macro? recur is designed to optimize tail call. Your function doesn't seem to allow (maybe I'm wrong). Although you said that you do not need it. Why do you want to explicitly replace your insertR * call with something else? If you don't like passing newkey oldkey every time (and they don't change), you can create an internal function that will use these keys.

0
source

All Articles