The second recursive call is already in the tail positions, you can just replace it with recur
.
(primefactors n (inc candidate))
becomes
(recur n (inc candidate))
Any overload function opens an implicit loop
block, so you do not need to insert it manually. This should already improve the stack situation, as this branch will be more widely used.
First recursion
(primefactors (/ n candidate))
not in the tail position, as its result is transmitted to conj
. To put it in the tail position, you will need to collect the primary coefficients in the extra argument of the accumulator, to which you conj
get the result from the current recursion level, and then go to recur
for each call. You will need to configure the termination condition to return this battery.
source share