0

I am messing around in language and need some help. I would like to create a swap function that swaps the first with the second. So if (swap '(a b c d e g)) should return (b a d c e g). I dont want to store any values doing it. Is there a function or way to do it in scheme? I have no idea if I would define a list like

(DEFINE list1 (LIST 'a 'b 'c 'd 'e ))

then not sure what to do

Harold B
  • 23
  • 8

1 Answers1

4

The trick is to process two elements at a time, swapping them and advancing two elements in the recursion. This is what I mean:

(define (swap lst)
        ; if the list is empty or has a single element
  (cond ((or (null? lst) (null? (cdr lst)))
        ; then return that list
         lst)
        ; otherwise build a new list
        (else
        ; by first adding the second element
         (cons (cadr lst)
        ; and then adding the first element
               (cons (car lst)
        ; finally, advance the recursion over two elements
                     (swap (cddr lst)))))))

I believe the sample output in the question is wrong, where does the f come from? For example the results I'd expect would be:

(swap '(a b c d e g))
=> '(b a d c g e)

(swap '(a b c d e))
=> '(b a d c e)

(swap '(a))
=> '(a)

(swap '())
=> '()
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • Oh im sorry your right. Thank you for your comments. helped me out alot. I never understand people with code by typing but you did a good job. – Harold B Apr 01 '14 at 21:27
  • I will. Another question actually. When you have if the cond is null? (cdr lst))) does that mean your taking out the first element in the list and putting the next 2? and what does cadr actually do. also would it be ok if you could email me at teamdv101@yahoo.com ? – Harold B Apr 01 '14 at 23:07
  • We must ask if `(null? (cdr lst))` in case the list has an odd number of elements, because the last (single) element can't be swapped in that case. `(cadr x)` is shorthand for `(car (cdr x))`, `(cddr x)` is shorthand for `(cdr (cdr x))`, and so on ... you get the idea. And sorry, but I don't answer questions by email – Óscar López Apr 01 '14 at 23:32