How would I write a Scheme procedure that takes a list and returns the list created by switching successive elements in the list?

Viewed 325

I am having trouble writing a Scheme procedure that takes a list and returns the list created by switching successive elements in the list.

For example, if I were to call: (newlist ‘((a b) (c d) e f g)) I would get: ‘( (b a) (d c) f e g)

I have tried the following so far, but I am getting an error when trying to compile:

(define (newlist givenList)
  (cond ; Condition statement
    ((null? givenList)
        '())
        ((null? (cdr givenList))
            (list (car givenList)))
        (list (cadr givenList) (car givenList)))
    (newlist (cddr givenList)))

cddr: contract violation expected: (cons/c any/c pair?) given: (g)

This language is very different from the ones I've previously worked with, so I'm admittedly a little stumped.

1 Answers

Your parenthesization is wrong. Here's what you wrote:

(define (newlist givenList)
  (cond ; Condition statement
      ( (null? givenList)
          '()
          )
      ( (null? (cdr givenList))
          (list (car givenList))
          )
      ( list                        ; NB
          (cadr givenList)
          (car givenList)
          ) )
  (newlist                          ; NB
     (cddr givenList)))

Judging by the error message, you use Racket. Clicking on an open bracket in its editor will highlight the expression to its ending bracket. Pressing "Alt-right arrow" will then make your cursor point jump to the closing bracket, and then pressing "Alt-left arrow", back to the opening one. This way you can see what's what, and reformat and add whitespace to make the code clearer for you.

In particular, your cond's third clause starts with list. It is tested for being false or true, and since it's not #f it is considered to be true. So the following two expressions will be evaluated, while the value of the first will be ignored.

Then, as we can now see, the value of the whole cond expression is ignored, and another form, (newlist ...) is evaluated -- unconditionally.

Related