I really need help with this coding here. I would be grateful to anyone who helps me out with this.
Use accumulative recursion to write a function, expand, that consumes a nonempty string and produces a string that has been reversed where there is a space between each character in the original string. For example (expand “Hi guys.â€) produces “. s y u g i H").
Do I have to convert the string into the list and then back again to make the code work or should I try to reverse the string as a string?
Help with scheme code.
Re: Help with scheme code.
While not necessary, it would certainly simplify things.helpneededhere wrote:Do I have to convert the string into the list and then back again to make the code work or should I try to reverse the string as a string?
Accumulative recursion just means that an extra parameter is passed to your function each time it is called; this extra parameter holds the accumulated result.
For example,
Code: Select all
(define (evens-in-list lis result)
(if (null? lis)
result
(evens-in-list (cdr lis)
(if (even? (car lis))
(cons (car lis) result)
result ))))
Now it is quite common that the user doesn't care to be bothered with having to specify the initial accumulated value, it is just needed in order for the recursion to keep track of the result. For this reason, you will often see the accumulated function defined within another function; one that doesn't have the accumulated result parameter.
Code: Select all
(define (evens-in-list lis)
(define (evens-in-list-iter lis result)
(if (null? lis)
result
(evens-in-list-iter (cdr lis)
(if (even? (car lis))
(cons (car lis) result)
result ))))
(evens-in-list-iter lis '()) )
Note that the -iter function could be defined completely separately (outside of 'evens-in-list'), but by placing it within 'evens-in-list', we keep things more organized. Also, the order of the even numbers in the result will be opposite how they appear in the original list, so you might want to 'reverse' them or perform other processing (by modifying the last line).
Now your function is going to be passed a list of characters, and needs to prepend both the character and a space to the result each time through the iteration. This is accomplished with something such as "(cons #\space (cons (car lis) result))". You may also have to test each original character to avoid duplicating spaces (per your example).