Scheme 方案Rswap功能
有人能帮我完成这个功能吗 使用类似于swap递归版本的scheme函数Scheme 方案Rswap功能,scheme,Scheme,有人能帮我完成这个功能吗 使用类似于swap递归版本的scheme函数 (reswap '((h i)(j k) l (m n o))) 应该回来 ((k j) (i h) (n m o) l) ; 及 应该回来 (c (b a) g ((f e) d) (i h))) 哈哈,这看起来是个好问题,但我得到的只是 (define (swap lst) ; if the list is empty or has a single element (cond ((or (nul
(reswap '((h i)(j k) l (m n o)))
应该回来
((k j) (i h) (n m o) l) ;
及
应该回来
(c (b a) g ((f e) d) (i h)))
哈哈,这看起来是个好问题,但我得到的只是
(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)
(else
; by first adding the second element
(cons (cadr lst)
(cons (car lst)
(swap (cddr lst)))))))
但这只是正常的交换 试试这个:
(define (rswap lst)
;; Create a helper function to do the recursive work.
(define (helper in out)
;; If the input is not a list, simply return it.
;; There is nothing to be done to rswap it.
(if (not (list? in))
in
;; If in is an empty list, simply return the out.
(if (null? in)
out
;; If in is a list with only one item, append
;; the result of calling rswap on the item to
;; out and return it.
(if (null? (cdr in))
(append out (list (rswap (car in))))
;; This is where the recursion continues.
;; Take two items off in before the next call.
;; rswap the two items and add them to out.
(helper
(cddr in)
(append out (list (rswap (cadr in)) (rswap (car in)))))))))
(helper lst '()))
你试过什么吗?如果是的话,请展示你试过的。你能看一下吗?(DEFINE(rswap lst)(COND((or)(NULL?lst)(NULL?(CDR lst)))lst);如果列表为空或单个元素,则将返回该列表(否则(CONS(CONS(CONS(CDR(CAR(CDR lst))))(CAR(CAR(CDR lst)))(CONS(CDR(CAR lst))(C$;获取第二个元素,然后添加第一个元素(rswap(CDDR lst))))))
(define (rswap lst)
;; Create a helper function to do the recursive work.
(define (helper in out)
;; If the input is not a list, simply return it.
;; There is nothing to be done to rswap it.
(if (not (list? in))
in
;; If in is an empty list, simply return the out.
(if (null? in)
out
;; If in is a list with only one item, append
;; the result of calling rswap on the item to
;; out and return it.
(if (null? (cdr in))
(append out (list (rswap (car in))))
;; This is where the recursion continues.
;; Take two items off in before the next call.
;; rswap the two items and add them to out.
(helper
(cddr in)
(append out (list (rswap (cadr in)) (rswap (car in)))))))))
(helper lst '()))