Lazy sequence or recur for mathematical power function?
- by StackedCrooked
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?