Skip to content

Instantly share code, notes, and snippets.

@sma
Created March 1, 2009 17:56
Show Gist options
  • Save sma/72416 to your computer and use it in GitHub Desktop.
Save sma/72416 to your computer and use it in GitHub Desktop.

Clojure now supports mutual recursive local functions using letfn:

(defn ring [n] 
  (letfn [(a [n] (if (zero? n) n (b (dec n)))) 
          (b [n] (if (zero? n) n (c (dec n)))) 
          (c [n] (if (zero? n) n (a (dec n))))] 
     (c n))) 
(ring 1000)

Using trampoline, you can even make this stackless:

(defn ring [n]
  (letfn [(a [n] #(if (zero? n) n (b (dec n)))) 
          (b [n] #(if (zero? n) n (c (dec n)))) 
          (c [n] #(if (zero? n) n (a (dec n))))] 
     (trampoline c n)))
(ring 100000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment