Lazy sequence or recur for mathematical power function?
Posted
by StackedCrooked
on Stack Overflow
See other posts from Stack Overflow
or by StackedCrooked
Published on 2010-05-08T20:55:51Z
Indexed on
2010/05/08
20:58 UTC
Read the original article
Hit count: 197
clojure
As an exercise I implemented the mathematical power function. Once using recur:
(defn power [a n]
(let [multiply (fn [x factor i]
(if (zero? i)
x
(recur (* x factor) factor (dec i))))]
(multiply a a (dec n))))
And once with lazy-seq:
(defn power [a n]
(letfn [(multiply [a factor]
(lazy-seq
(cons a (multiply (* a factor) factor))))]
(nth (multiply a a) (dec n))))
Which implementation do you think is superior? I truly have no idea.. (I'd use recur because it's easier to understand.)
I read that lazy-seq is fast because is uses internal caching. But I don't see any opportunities for caching in my sample. Am I overlooking something?
© Stack Overflow or respective owner