"pure recursion" is a made-up term here, please forgive.
Here are two examples using two different recursion approaches. What are the guidelines of usage of one over another?
(defn take-while
"Returns a lazy sequence of successive items from coll while
(pred item) returns true. pred must be free of side-effects."
{:added "1.0"
:static true}
[pred coll]
(lazy-seq
(when-let [s (seq coll)]
(when (pred (first s))
(cons (first s) (take-while pred (rest s)))))))
(defn take-last
"Returns a seq of the last n items in coll. Depending on the type
of coll may be no better than linear time. For vectors, see also subvec."
{:added "1.1"
:static true}
[n coll]
(loop [s (seq coll), lead (seq (drop n coll))]
(if lead
(recur (next s) (next lead))
s)))
Recursion is a better way of solving a problem as compared to looping . In most cases time complexity of a recursive solution is better than the loop one . Most of the software company in their interviews prefer a recursive solution.
No, recursion isn't faster than loops, because loops have built-in support in CPUs, whereas recursion is implemented using the generally slower function call / return mechanism. That said, recursion can be made to be as fast as loops by a good compiler, when the code is properly written.
In general, no, recursion will not be faster than a loop in any realistic usage that has viable implementations in both forms. I mean, sure, you could code up loops that take forever, but there would be better ways to implement the same loop that could outperform any implementation of the same problem via recursion.
Is a while loop intrinsically a recursion? then, yes, a while loop is a form of recursion. Recursive functions are another form of recursion (another example of recursive definition).
A few factors to consider:
StackOverflowError
The only one reason to use lazy-seq
/lazy-cons
mechanism is generating lazy sequences. If you don't need them then loop
/recur
should undoubtedly be used.
Use plain recursion when you are writing your function in the first place. Then change this to recur once you have it all working, if you can.
One problem with TCO is that if you balk your recursion up, you get an infinite look. Without, your code crashes nicely with a stack overflow, which is what you want. I didn't like the idea of recur when I first heard about it --most optimisations should just happen -- but being able to switch it off is nice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With