想在编程中交换元素

时间:2014-04-01 19:30:09

标签: functional-programming scheme

我在语言上乱七八糟,需要一些帮助。我想创建一个交换函数,将第一个交换为第二个。所以如果(交换'(a b c d e g)) 应该返回(b a d c e g)。我不想存储任何值。方案中是否有功能或方法?我不知道是否要定义像

这样的列表

(DEFINE list1(列表'a'b'c'd'e))

然后不知道该怎么做

1 个答案:

答案 0 :(得分:4)

诀窍是一次处理两个元素,交换它们并在递归中推进两个元素。这就是我的意思:

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

我认为问题中的示例输出是错误的,f来自何处?例如,我预期的结果将是:

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