LISP:多级递归反向函数 [英] LISP: multi-level recursive reverse function

查看:73
本文介绍了LISP:多级递归反向函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何反转列表,以使每个子列表也都反转?这是我到目前为止的内容:

How to reverse a list such that every sublist is also reversed? This is what I have so far:

(defun REV (L)
  (cond
    ((null L) nil)
    ((listp L)
     (append
      (REV (cdr L))
      (list (car L))))
    (t
     (append
      (REV (cdr L)) 
      (list (car L))))))

推荐答案

您处在正确的轨道上,但是您的最后两个条件具有相同的操作,这应表明它们中的一个未按应做.的确,第二个条件listp情况不正确,因为当它是一个列表时,您需要附加该列表的相反部分而不是未修改的列表.可能的解决方案:

You are on the right track, but your last two conditions have the same action, which should give an indication that one of them is not doing what it should. Indeed, the second condition, the listp case, is not right, because when it's a list, you need to append the reverse of that list instead of the unmodified list. A possible solution:

(defun reverse (l)
  (cond ((null? l) nil)
        ((listp (car l)) (append (reverse (cdr l)) 
                                 (list (reverse (car l)))))
        (t
          (append (reverse (cdr l)) 
                  (list (car l))))))

>  (reverse '((1 2 3) (4 5 6)))
((6 5 4) (3 2 1))

如您所见,唯一的区别是您可以测试第一个元素是否为列表,如果是,则在添加第一个元素之前先对其进行反转.

As you can see, the only difference is that you test if the first element is a list, and if it is, you reverse the first element before appending it.

这篇关于LISP:多级递归反向函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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