This is the code for single integer, how can it extend to arbitrarily large input by passing list as a parameter?
(define (factors n)
(define (*factors d)
(cond ((> d n) (list))
((= (modulo n d) 0) (cons d (*factors (+ d 1))))
(else (*factors (+ d 1)))))
(*factors 1))
(display (factors 1111111))
(newline)
"...how can it extend to arbitrarily large input by passing list as a parameter?"
The process described by the posted
*factorsprocedure is not iterative, i.e., not tail-recursive, and it will grow stack space for large inputs. I take it that OP is interested in finding a tail-recursive version of this code to improve the space efficiency.You can convert this to an iterative process by adding an accumulator to the helper procedure. This allows results to be stored in the accumulator and passed through recursive calls without the need for any further operations when those calls return, i.e., tail recursion.
Here are the results of tracing the execution of these procedures:
Here
factors-traceandfactors-iter-traceare slightly modified versions of thefactorsandfactors-iterdefinitions, allowing for a trace. You can see that the%factorsprocess grows in stack size as the computation progresses, butitermaintains a constant stack size.As others have already answered, the easiest way to use
factors-iterwith a list of inputs is to usemap: