Learner_51
Learner_51

Reputation: 1075

How to print a string in backward, in scheme?

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)

Upvotes: 2

Views: 8956

Answers (4)

Joel J. Adamson
Joel J. Adamson

Reputation: 723

Is this what you want?

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

Upvotes: 4

Jerry Coffin
Jerry Coffin

Reputation: 490088

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?

Upvotes: 1

Learner_51
Learner_51

Reputation: 1075

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

Upvotes: 1

deinst
deinst

Reputation: 18782

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

Upvotes: 6

Related Questions