Would like to swap elements in programming [closed

2019-06-09 16:07发布

问题:

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

回答1:

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 '())
=> '()