方案 Rswap 功能 [英] Scheme Rswap function

查看:52
本文介绍了方案 Rswap 功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人帮我做这个功能吗?

Someone please help me with this function?

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

use scheme function that behaves like a recursive version of swap.

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

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

这篇关于方案 Rswap 功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆