递归拆分列表功能LISP [英] Recursive split-list function LISP

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

问题描述

split-list函数获取一个列表,并返回由输入的交替元素组成的两个列表的列表.我写了以下内容:

The split-list function takes a list and returns a list of two lists consisting of alternating elements of the input. I wrote the following:

(defun split-list (L)
  (cond
      ((endp L) (list NIL  NIL))
      (t (let ((X (split-list (cdr L))))
         (cond
             ((oddp (length L))
              (list (cons (first L) (first X)) (cadr X)))
             (t (list (first X) (cons (first L) (cadr X)))))))))

对于奇数编号的列表,输出是预期的,第一个列表由第1、3、5等元素组成,第二部分由第2、4、6等组成.但是对于偶数列表,第1、2nd ,3rd ..在返回列表的右侧,其余部分在左侧.

The output is as expected for odd numbered lists, the first list consisting of the 1st, 3rd, 5th etc elements and the second part consisting of the 2nd, 4th, 6th etc. With an even list however, the 1st, 2nd ,3rd.. are on the right of the returned lists with the rest on the left.

例如:

(SPLIT-LIST '(a b c 1 2 3))
(SPLIT-LIST RETURNED ((b 1 3) (a c 2))

该订单应调换.我缺少逻辑上的重大缺陷吗?我可以在不进行重大更改的情况下纠正这种情况吗?

the order should be swapped. Is there a major flaw in my logic that I'm missing? Can I rectify this situation without making major alterations?

推荐答案

是的,您无需进行重大修改即可纠正此问题.

Yes, you can rectify the problem without major modifications.

  1. (endp (cdr L))
  2. 添加案例
  3. cddr L
  4. 上进行递归调用
  5. 之后,else案例将始终包含两个新元素,一个要包含在每个列表中;另一个要包含在每个列表中.不再需要length通话
  1. Add a case for (endp (cdr L))
  2. Do the recursive call on cddr L
  3. After that, the else case will always have two new elements, one to cons onto each list; there is no more need for the length call

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

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