My question is: how to write a procedure that utilises tailcall, and that constructs a list not in the reverse order. To show what I mean, here is an example of a very simple procedure that is iterative, and that creates a copy of a list:
(define (copy-list ls)
(define (iter cp-ls rest-ls)
(if (null? rest-ls)
cp-ls
(iter (cons (car rest-ls) cp-ls) (cdr rest-ls))))
(iter '() ls))
The problem is that, due to the iterative order in which the elements are cons
ed together, the returned list ends up reversed. Yes, you could easily solve this by doing (reverse cp-list)
instead of just cp-list
in the if
-block, but the problem with this is that reverse
is a recursive process. Utilising this procedure will nullify the tailcall advantage, which is that the stack size grows linearly with the input size.
So, basically, how to write a procedure like the one mentioned that returns the list in correct order without utilising any sort of recursive processes?
Thanks