Created
December 5, 2013 12:12
-
-
Save akonring/7804273 to your computer and use it in GitHub Desktop.
Different faculty implementations using Clojure
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
;; The direct style recursion faculty function | |
(defn fac-ds [n] | |
(if (zero? n) 1 | |
(* n (fac (dec n))))) | |
(fac 5) | |
;; => 120 | |
;; The tail recursive faculty function | |
(defn fac-tail [n] | |
(loop [k n acc 1] | |
(if (zero? k) acc | |
(recur (dec k) (* acc k))))) | |
(fac-tail 5) | |
;; => 120 | |
;; Can we use clojures lazy sequences? | |
;; Yes we can! | |
(defn fac-lazy [n] | |
(reduce * (range (bigint 1) (inc n)))) | |
(fac-lazy 5) | |
;; => 120 | |
;; What about a continuation? | |
(defn fac-cps [n k] | |
(if (zero? n) (k 1) | |
(fac-cps (dec n) (fn [v] (k (* n v)))))) | |
(defn fac-cps-identity [n] | |
(fac-cps n #(identity %))) | |
(fac-cps-identity 5) | |
;; => 120 | |
;; Lets benchmark the functions to test | |
;; how clojure and the JVM performs | |
(defn time-function [fn n] | |
(do | |
(prn "Timing the function") | |
(time (fn n)) | |
(prn "Done computing"))) | |
(time-function fac-cps-identity (bigint 2000)) | |
;; => "Timing the function" | |
;; "Elapsed time: 4.142 msecs" | |
;; "Done computing" | |
;; nil | |
(time-function fac-lazy (bigint 2000)) | |
;; "Timing the function" | |
;; "Elapsed time: 7.149 msecs" | |
;; "Done computing" | |
;; nil | |
(time-function fac-tail (bigint 2000)) | |
;; "Timing the function" | |
;; "Elapsed time: 7.807 msecs" | |
;; "Done computing" | |
;; nil | |
(time-function fac-ds (bigint 2000)) | |
;; "Timing the function" | |
;; "Elapsed time: 3.838 msecs" | |
;; "Done computing" | |
;; nil | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment