17

Can somebody rewrite this (plt) Scheme code into Clojure?

(define (f n)
   (printf "(f ~a)~n" n)
   (g n))

(define (g n)
   (printf "(g ~a)~n" n)
   (h n))

(define (h n)
   (printf "(h ~a)~n" n)
   (f (+ n 1)))

In such a way as to not collapse the procedures f, g, and h together and to allow the code to run indefinitely without crashing?

1 Answer 1

30

Use a trampoline:

(declare f)

(defn h [n]
   (println "(h " n ")")
   #(f (+ n 1)))

(defn g [n]
   (println "(g " n ")")
   #(h n))

(defn f [n]
   (println "(f " n ")")
   #(g n))

Kick it off with:

(trampoline f 0)

I've had this code running on my pc in the background for about 5 hours now and the memory usage is flat.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.