Question

I'm have the idea down, I'm just a little stuck on the execution. What I need to do is swap every 2 pairs of the list. For example (1 2 3 4 5 6) becomes (2 1 4 3 6 5)

I have swapping of the first 2 pairs working and what I'm planning to do is swap the first 2, then the next 2, etc. then appending it. I'm not sure how to go about this. Any help is appreciated, here's my code so far. I know there probably needs to be a recursion in there but how do I set the pairs to a variable so I could append later or is append already doing that?

(define (swapPairs L)
   (cond ((null? L)
          '())
        (cons (cadr L) (cons (car L) (cddr L))))

(define (appendTo L x)
   (if (null? L) 
          (cons x L)
        (cons (car L) (appendTo (cdr L) x))))
Was it helpful?

Solution

You cannot check only if the list is null but also if the cdr is null as well. Instead of just using cddr you should put that list with the pairs swapped. Ie. a recursion:

(define (swap-every-2 lst)
  (if (or (null? lst) 
          (null? (cdr lst)))
      lst
      (list* (cadr lst) 
             (car lst) 
             (swap-every-2 (cddr lst)))))

(swap-every-2 '())              ; ==> ()
(swap-every-2 '(a))             ; ==> (a)
(swap-every-2 '(a 1 b 2 c 3))   ; ==> (1 a 2 b 3 c)
(swap-every-2 '(a 1 b 2 c 3 d)) ; ==> (1 a 2 b 3 c d)

Using pairs in this context is slightly strange for me as I'm thinking an association list. eg. ((a . 1) (b . 2) (c . 3)) and it can be swapped with (map (lambda (x) (cons (cdr x) (car x))) lst)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top