How to print a string in backward, in scheme?

不羁的心 提交于 2019-12-22 23:11:23

问题


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)


回答1:


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




回答2:


Is this what you want?

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



回答3:


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



回答4:


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?



来源:https://stackoverflow.com/questions/3384173/how-to-print-a-string-in-backward-in-scheme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!