Last active
August 29, 2015 14:23
-
-
Save Risto-Stevcev/b63ffbac95fb731971b5 to your computer and use it in GitHub Desktop.
Loop-recur TCO for self-referencing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;;;; 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