I am extremely new at scheme and I am doing this problem from here:

Write a procedure switch that takes a sentence as its argument and returns a sentence in which every instance of the words I or me is replaced by you, while every instance of you is replaced by me except at the beginning of the sentence, where it’s replaced by I. (Don’t worry about capitalization of letters.) Example:

(switch ’(You told me that I should wake you up))
(i told you that you should wake me up)

I used additional functions from here.

(define (switchnext n)
(cond ((empty? n) '())
    ((or (equal? (first n) 'you) (equal? (first n) 'You)) (se 'me (switchnext (bf n))))
    ((or (equal? (first n) 'i) (equal? (first n) 'I) (equal? (first n) 'me)) (se 'you (switchnext (bf n))))
(else (se (first n) (switchnext (bf n))))))

(define (switch n)
(cond ((empty? n) '())
    ((or (equal? (first n) 'you) (equal? (first n) 'You)) (se 'i (switchnext (bf n))))
(else (se (first n) (switchnext (bf n))))))

I absolutely hate this code; I feel it is too repetitive. I think part of it is because I probably have no way of knowing when is beginning of a sentence. How can I improve this code?


1 Answer 1


It'd be easier to separate this into two parts. First, we can do all the word transformations using map and a single word switcher:

(define (switch-word word)
  (cond ((equal? word 'I) 'you)
        ((equal? word 'me) 'you)
        ((equal? word 'Me) 'you)
        ((equal? word 'you) 'me)
        ((equal? word 'You) 'me)
        (else word)))

(define (switch sentence)
    (map switch-word sentence))'

That handles all the word swapping in one go, without having to write the iteration code yourself.

Now all we need to do is change the first word from me to I, if appropriate:

(define (me-to-I word)
    (if (equal? word 'me) 'I word))

(define (switch sentence)
    (let ((switched (map switch-word sentence)))
        (cons (me-to-I (car switched)) (cdr switched))))
  • \$\begingroup\$ I haven't learned about map yet. Thanks though \$\endgroup\$ Dec 9, 2015 at 17:13
  • 1
    \$\begingroup\$ @morbidCode It's pretty foundational for functional programming. If you don't want to use the library function, you could always provide your own implementation, it's pretty short. \$\endgroup\$
    – Barry
    Dec 9, 2015 at 17:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.