简体   繁体   English

用球拍中的append交换对

[英]Swapping pairs with append in Racket

I'm have the idea down, I'm just a little stuck on the execution. 我的想法不对,我对执行只停留了一点。 What I need to do is swap every 2 pairs of the list. 我需要做的是交换列表的每两对。 For example (1 2 3 4 5 6) becomes (2 1 4 3 6 5) 例如(1 2 3 4 5 6)变成(2 1 4 3 6 5)

I have swapping of the first 2 pairs working and what I'm planning to do is swap the first 2, then the next 2, etc. then appending it. 我已经交换了前两对,并且我打算做的是交换前两对,然后交换第二对,依此类推,然后追加。 I'm not sure how to go about this. 我不确定该怎么做。 Any help is appreciated, here's my code so far. 感谢您的帮助,到目前为止,这是我的代码。 I know there probably needs to be a recursion in there but how do I set the pairs to a variable so I could append later or is append already doing that? 我知道那里可能需要递归,但是如何将对设置为变量,以便以后可以追加或已经追加了呢?

(define (swapPairs L)
   (cond ((null? L)
          '())
        (cons (cadr L) (cons (car L) (cddr L))))

(define (appendTo L x)
   (if (null? L) 
          (cons x L)
        (cons (car L) (appendTo (cdr L) x))))

You cannot check only if the list is null but also if the cdr is null as well. 您不仅不能检查列表是否为空,还不能检查cdr是否也为空。 Instead of just using cddr you should put that list with the pairs swapped. 而不是仅使用cddr您应该将列表替换成对。 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. 在这种情况下使用pairs我来说有点奇怪,因为我正在考虑关联列表。 eg. 例如。 ((a . 1) (b . 2) (c . 3)) and it can be swapped with (map (lambda (x) (cons (cdr x) (car x))) lst) ((a . 1) (b . 2) (c . 3))并且可以与(map (lambda (x) (cons (cdr x) (car x))) lst)交换(map (lambda (x) (cons (cdr x) (car x))) lst)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM