Racket Error: expects a non-empty list but given empty
Racket Error: expects a non-empty list but given empty
我正在编写一个程序,它要求我将 str 中的所有大写字母转换为小写字母,将小写字母转换为大写字母,所有其他字符保持不变。
下面是我的代码:
(define (switch-case str)
(list->string (switch-char (string->list str))))
(define (switch-char loc)
(cons
(cond
[(empty? (first loc)) empty]
[(char-lower-case? (first loc)) (char-upcase (first loc))]
[(char-upper-case? (first loc)) (char-downcase (first loc))]
[else (first loc)]) (switch-char (rest loc))))
并且 (switch-case "ABC") 的错误消息是:
first: expects a non-empty list; given: empty
有人可以帮我解决这个问题吗?不知道哪部分代码错了:(
您的代码中存在多个语法错误。我建议你花更多的时间研究 Scheme 的基本语法,以及如何构造递归过程。请注意:
- 开头那个
cons
不应该出现
- 基本情况错误,您应该要求
(empty? loc)
。
- 最后一种情况不正确,
else
不是这样使用的。
- 最严重的错误是:您忘记了在所有情况下都调用递归。 那是
cons
发挥作用的地方!
此版本解决了上述所有问题:
(define (switch-char loc)
(cond
[(empty? loc) empty]
[(char-lower-case? (first loc))
(cons (char-upcase (first loc)) (switch-char (rest loc)))]
[(char-upper-case? (first loc))
(cons (char-downcase (first loc)) (switch-char (rest loc)))]
[else (cons (first loc) (switch-char (rest loc)))]))
我正在编写一个程序,它要求我将 str 中的所有大写字母转换为小写字母,将小写字母转换为大写字母,所有其他字符保持不变。 下面是我的代码:
(define (switch-case str)
(list->string (switch-char (string->list str))))
(define (switch-char loc)
(cons
(cond
[(empty? (first loc)) empty]
[(char-lower-case? (first loc)) (char-upcase (first loc))]
[(char-upper-case? (first loc)) (char-downcase (first loc))]
[else (first loc)]) (switch-char (rest loc))))
并且 (switch-case "ABC") 的错误消息是:
first: expects a non-empty list; given: empty
有人可以帮我解决这个问题吗?不知道哪部分代码错了:(
您的代码中存在多个语法错误。我建议你花更多的时间研究 Scheme 的基本语法,以及如何构造递归过程。请注意:
- 开头那个
cons
不应该出现 - 基本情况错误,您应该要求
(empty? loc)
。 - 最后一种情况不正确,
else
不是这样使用的。 - 最严重的错误是:您忘记了在所有情况下都调用递归。 那是
cons
发挥作用的地方!
此版本解决了上述所有问题:
(define (switch-char loc)
(cond
[(empty? loc) empty]
[(char-lower-case? (first loc))
(cons (char-upcase (first loc)) (switch-char (rest loc)))]
[(char-upper-case? (first loc))
(cons (char-downcase (first loc)) (switch-char (rest loc)))]
[else (cons (first loc) (switch-char (rest loc)))]))