切换字符串的大写和小写

时间:2019-10-10 20:52:20

标签: racket

我正在做一个问题,要求我将字符串中的所有大写字母都转换为小写字母,并将小写字母转换为大写字母,而所有其他字符都保持不变。

下面是我的代码:

(define (switch-case str)
  (list->string
  (cons
  (cond
    [(char-lower-case? (first (string->list str))) (char-upcase (first 
(string->list str)))]
    [(char-upper-case? (first (string->list str))) (char-downcase (first 
(string->list str)))]
    [else (first (string->list str))])
  (switch-case (rest (string->list str))))))

str“ ABC”的错误消息是:     字符串->列表:期望给出一个字符串(cons#\ B(cons#\ C空)) 有人可以告诉我我的代码出了什么问题吗?谢谢

1 个答案:

答案 0 :(得分:1)

递归调用的类型错误。您将[List-of Character]传递给switch-case,但是期望String

; String -> String
(define (switch-case str)
  (list->string
   (cons
    (swapcase nestr)
    (switch-case
     (rest (string->list str)) ; the type of this expression is [List-of Character]
                 ))))

遵循此模板:

; [List-of Character] -> [List-of Character]
(define (switch-case-charlist cl)
  (cond [(empty? cl) ...]
        [else (... (first cl) ... (switch-case-charlist (rest cl)))]))

; Character -> Character
(define (swap-case-character c)
  ...)

; String -> String
(define (swap-case-string s)
  (list->string (... (string->list s))))