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)