【问题标题】:Scheme Rswap function [closed]方案 Rswap 功能 [关闭]
【发布时间】:2014-04-07 02:50:03
【问题描述】:

有人请帮我完成这个功能吗?

使用类似于交换递归版本的方案函数。

(reswap '((h i)(j k) l (m n o)))

应该返回

((k j) (i h) (n m o) l) ;

(reswap '((a b) c (d (e f)) g (h i)))

应该返回

(c (b a) g ((f e) d) (i h))) 

【问题讨论】:

  • 您尝试过什么吗?如果是,请展示您的尝试。
  • 你能看一下吗? (DEFINE(rswap lst) (COND ((or(NULL?lst) (NULL?(CDR lst))) lst) ;如果列表为空或单个元素,则返回该列表 (ELSE (CONS (CONS(CDR(CAR (CDR lst)))(CAR(CAR(CDR lst)))) (CONS (CDR(CAR lst))(C$ ;获取第二个元素,然后添加第一个元素 (rswap (CDDR lst)) ))) ))

标签: scheme


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    哈哈,这看起来是个好问题,但我得到的只是

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

    但这只是正常的交换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 1970-01-01
      • 2011-06-27
      • 1970-01-01
      • 1970-01-01
      • 2016-07-05
      • 2015-05-04
      相关资源
      最近更新 更多