I know if I write my scheme code in the following way and type in (word ‘(a b c)), it will out put the list in the same order. Could you please tell me if there was a way I can print it out in opposite order. Ex- (list ‘c ‘b ‘a).
it needs to be the user's input I print out in opposite order. So, I can't call it (reverse '(a b c)). since the user input can be something like '(x y z).
Thanks a lot.
(define(word x )
(if(null? x) x
(cons(car x)(word (cdr x)))))
(word '(a b c))
(list 'a 'b 'c)
(reverse '(a b c))
will reverse your string. However I suspect that this is probably homework and you are supposed to write your own reverse
function.
If so, can you reverse an empty list? If you have a list and have the reverse of the rest of the list, can you get the reverse of the whole list? Can you see how to make a function that reverses the list from these pieces?
Is this what you want?
(list->string (reverse (string->list "market")))
"tekram"
Thanks all for your information and help. I found a way to do it. just in-case there was anyone else looking.
(define (word lis)
(if (null? lis)
'()
(append (word (cdr lis))
(list (car lis)))))
Hint: cons
creates a list composed of its first argument followed by its second argument. Right now, you're using it to create a list of the first element followed by the same function applied to the rest of the elements, and that creates a list in the same order as it was.
What do you suppose would happen if you created a list of the same function applied to the rest of the elements followed by the first element?