I want to write string reverse function without using either append or reverse functions.
I wrote the code as follows:
> (define rdc(lambda (ls)
(cond((null? ls) '())
(else (cons (rdc (cdr ls)) (car ls))))))
The output for this code is as follows:
Input: > (rdc '(a b c))
Output: (((() . c) . b) . a)
But I want output in the form of (c b a). I’m using DrScheme
Your solution is performing the
consoperation in the wrong order, that’s why the result is not a well-formed list.The correct answer is simple using an accumulator for storing the answer – with the nice side effect that this is a tail-recursive solution:
The previous procedure uses a named let for implementing the recursion. Alternatively, you could use an inner helper procedure, this version is completely equivalent:
Either way, this works: