想在编程中交换元素 [英] Would like to swap elements in programming
问题描述
我在用语言搞乱,需要一些帮助。我想创建一个交换函数,第一个交换与第二个交换。所以如果(交换'(a b c d e g))
应该返回(b a d c e g)。我不想存储任何值。在方案中有没有功能或方法?我不知道是否我会定义一个像
(DEFINE list1(LIST'a'b'c'd'e))
然后不知道该怎么办
诀窍是一次处理两个元素,交换它们并推进递归中的两个元素。这就是我的意思:
(define(swap lst)
;如果列表为空或有单个元素
(cond((或(null?lst)(null?(cdr lst)))
;然后返回该列表
lst)
;否则建立一个新列表
(else
;首先添加第二个元素
(cons(cadr lst)
;然后添加第一个元素
(cons(car lst)
;最后,将递归推进到两个元素
(swap(cddr lst)))))))
我相信问题中的示例输出是错误的, f
来自哪里?例如,我期望得到的结果是:
$ b $ pre> (swap'(a b c d e g))
=> '(b a d c g e)
(swap'(a b c d e))
=> '(b a d c e)
(掉期'(a))
=> '(a)
(swap'())
=> '()
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
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 '())
=> '()
这篇关于想在编程中交换元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!