Would like to swap elements in programming [closed]

筅森魡賤 提交于 2019-12-08 12:28:40

问题


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


来源:https://stackoverflow.com/questions/22795186/would-like-to-swap-elements-in-programming

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!