开发者

Generic function for self-calling a recursive function in definition

开发者 https://www.devze.com 2023-03-06 23:39 出处:网络
Is there a reader macro or core function in Clojure that is similar to recur but possible with non-tail position?

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

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) (i开发者_如何学CnsertR* newkey oldkey (rest l))))    
    :else
        (cons (insertR* newkey oldkey (first l)) (insertR* newkey oldkey (rest l)))))

Is there some generic function I can use to call itself instead of calling insertR* explicitly?


Your question is unclear. If you mean: Can I do this without using stack space? No. Your insertR* has multiple self-calls, and that's impossible to express 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 stack? Not really. You could write it yourself, though. Something like:

(defmacro defrec [name & fntail]
  `(def ~name (fn ~'recurse ~@fntail)))

(defrec foo [x]
  (when-not (zero? x)
    (recurse (dec x))))

I suspect this has a few holes, but it does basically what you're thinking.


Why do you need this kind of function/macro? recur is created for tail-call optimization. It seems that your function doesn't allow it (may be I'm wrong). Though you said you don't need it. Why do you want to replace your calling insertR* explicitly to something else? If you don't like passing newkey oldkey every time (and they not changed) you can create inner function, which will use this keys.

0

精彩评论

暂无评论...
验证码 换一张
取 消