views:

150

answers:

5

Hi, 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)

+4  A: 
(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?

deinst
+1  A: 

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?

Jerry Coffin
`cons` does not create a list but a cons cell. Other than that, good hint.
Svante
A: 

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)))))
Oh! This is truly horrible. Please don't turn this in.
John Clements
+1  A: 

Is this what you want?

 (list->string (reverse (string->list "market")))
 "tekram"
Joel J. Adamson
A: 

John Clements, you should give that guy a solution if you think it is truly horrible. I think that guy's code is perfectly good. You should get an interpreter like DrRacket, then copy and paste his code. Then type in (word '(a b c d)). Output will be (list 'd 'c 'b 'a). Not sure why you said that code didn't work?