Say I have a function like this:
user=> (def m {10 5, 5 2, 2 1})
#'user/m
user=> (defn hierarchy [x] (when x (cons x (hierarchy (get m x)))))
#'user/hierarchy
user=> (hierarchy 10)
(10 5 2 1)
user=>
And obviously this is fine here because the stack depth will be small. But for this general type of problem, where I'm building a list that I want to return, the recursive call always ends up inside a cons call. How would I convert this to tail recursion, so that I can use recur and not take stack space?
Read up on accumulators.
In Clojure this specific problem could be solved by using lazy-seq
. lazy-seq
defers the computation, so stack overflows are (usually) not an issue.
(defn hierarchy
[x]
(when x
(lazy-seq
(cons x (hierarchy (get m x))))))
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