开发者

Changing certain letters in a string

Edit:

开发者_如何学编程
(define leet-helper
  (lambda (string)
    (cond
      [(null? (string->list string)) ""]
      [(equal? (car string)#\e)
       (cons 3 (leet-speak (cdr string)))]
      [(equal?  (car string) #\s)
       (cons 5 (leet-speak (cdr string)))]
      [(equal? (car string) #\o)
       (cons 0 (leet-speak (cdr string)))]
      [else string])))

(define leet-speak
  (lambda (string)
    (list->string (string->list (leet-speak string)))))

I'm working on a problem that takes a string and returns the same string with all e's turned into 3's, all s's turned into 5's, and all o's turned into 0's. I posted what I have created so far, but I keep getting errors when I try to test this so I know I'm not doing something right. Also.. this code has 3 separate conditionals, but if the string given is "eso", I want all 3 characters to be changed, not just the 'e'. I'm not sure how to do that, or if my recursion will take care of that by itself [?]. Any pointers would be appreciated!

(define leet-speak
  (lambda (string)
    (cond
      [(null? (string->list string)) ""]
      [(equal? (car (string->list string)) 'e) 
       (list->string (cons 3 (leet-speak (cdr (string->list string)))))]
      [(equal? (string->list (car string)) 's)
       (list->string (cons 5 (leet-speak (cdr (string->list string)))))]
      [(equal? (string->list (car string)) 'o)
       (list->string (cons 0 (leet-speak (cdr (string->list string)))))])))


Now suppose that we test your program (by stepping manually) with a string "test". The first error we see is that you have no else case. Second, you will notice that when you compare (car (string->list string)) with 'e you will always get false because when a string is decomposed it is decomposed as characters (#\e) and not symbols.

I would suggest that when you test your code, take note of the errors that you keep getting (what kind of errors? you don't mention them in your question; scheme is usually pretty informative with its error messages) and try to fix each of them. For instance, if you get

string->list : expects argument of type <string>; given myinput

then you know that there is something wrong with the type of myinput that you are giving string->list. This type of errors occurs a few time in your code. One way that I like to use when I have problems with recursion input types is to use helper functions/wrapper function (hint).

Moreover, a good way to test recursive programs is to run through them manually (e.g. with a string "test", as mentioned in the beginning) and then see where you get stuck and fix the program accordingly.

I hope that this will help set you in the right direction, and let me know if you need more pointers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜