Skip to content

Instantly share code, notes, and snippets.

@Risto-Stevcev
Last active August 29, 2015 14:23
Show Gist options
  • Save Risto-Stevcev/b63ffbac95fb731971b5 to your computer and use it in GitHub Desktop.
Save Risto-Stevcev/b63ffbac95fb731971b5 to your computer and use it in GitHub Desktop.
Loop-recur TCO for self-referencing
;;;; Partial Tail Call Optimization in Clojure
;; See this for why no full implicit TCO: https://groups.google.com/forum/#!msg/clojure/4bSdsbperNE/tXdcmbiv4g0J
; Naive non-optimized tail-recursive factorial function
(defn naive-factorial
([n] (naive-factorial n 1))
([n acc]
(if (zero? n)
acc
(naive-factorial (- n 1) (* acc n)))))
; Optimized factorial function using the loop-recur special form
(def factorial
(fn [n]
(loop [cnt n acc 1]
(if (zero? cnt)
acc
(recur (dec cnt) (* acc cnt))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment