(ns power.examples)
(defn non-acc-pow [base exp]
(if (zero? exp)
1
(* base (non-acc-pow base (dec exp)))))
(defn acc-pow [base exp]
(letfn [(loop [base exp acc]
(if (zero? exp)
acc
(recur base (dec exp) (* base acc))))]
(loop base exp 1)))
(defn lazy-pow [base exp]
(letfn [(loop [cur]
(cons cur (lazy-seq (loop (* cur base)))))]
(nth (take exp (loop base)) (dec exp))))
(defn iter-pow [base exp]
(nth (take exp (iterate (partial * base) base)) (dec exp)))
(defn apply-pow [base exp]
(apply * (repeat exp base)))
(= 16
(non-acc-pow 2 4)
(acc-pow 2 4)
(lazy-pow 2 4)
(iter-pow 2 4)
(apply-pow 2 4))
Originally posted here:
http://www.wisdomandwonder.com/article/6430/which-power-function-is-right-for-clojure
--
((λ (x) (x x)) (λ (x) (x x)))
http://www.wisdomandwonder.com/
ACM, AMA, COG, IEEE
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en