0
votes

I'm writing a program where it asks me to convert all the uppercase letters in str to lowercase and lowercase to uppercase, and all other characters remain the same. Below is my code:

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

And the error message for (switch-case "ABC") is:

first: expects a non-empty list; given: empty

Can someone help me with this? I don't know which part of the code is wrong:(

1

1 Answers

1
votes

There are several syntax errors in your code. I'd suggest you spend more time studying the basic syntax of Scheme, and how to construct a recursive procedure. Notice that:

  • That cons at the beginning shouldn't be there.
  • The base case is wrong, you should ask for (empty? loc) instead.
  • The last case is incorrect, that's not how else is used.
  • And the most serious mistake: you forgot to call the recursion in all cases. That's the point where cons comes into play!

This version addresses all the issues mentioned above:

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