2

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 Answers 4

6
(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?

4

Is this what you want?

 (list->string (reverse (string->list "market")))
 "tekram"
1

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)))))
3
  • 3
    Oh! This is truly horrible. Please don't turn this in. Aug 2, 2010 at 20:47
  • @JohnClements What exactly makes it horrible? Using append (due to its time complexity)? The recursive application not being in tail position? car and cdr instead of first and rest? Something else? (I'm a newbie Racketeer, so I'd like to learn.) Apr 22, 2017 at 10:35
  • 1
    You're right, I wasn't being helpful at all. This solution takes n^2 time. Doing better requires using an accumulator, which makes it linear. In retrospect, I wish I hadn't said this. :) Apr 22, 2017 at 23:11
1

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?

1
  • 1
    cons does not create a list but a cons cell. Other than that, good hint.
    – Svante
    Aug 2, 2010 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.