扁平化Lisp中的列表 [英] flatten list in lisp

查看:90
本文介绍了扁平化Lisp中的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在考虑将Lisp中的列表弄平.

So I've been looking at flattening a list in lisp.

但是,我想做的是逐级展开列表.

However, what I wanted to do is flatten a list level by level.

所以不是

(flatten '(a (b (d (g f))) e)) = (a b d g f e)

我要

(flatten '(a (b (d (g f))) e)) = (a b (d (g f )) e )

关于如何做到这一点的任何想法?

Any idea on how to do this guys?

非常感谢=)

推荐答案

您可以执行以下操作,例如:

You could do something like this, for example:

(defun fletten-level (tree)
  (loop for e in tree
        nconc
        (if (consp e)
            (copy-list e)
          (list e))))

(fletten-level '(a (b (d (g f))) e))
;; (A B (D (G F)) E)

这会循环遍历原始树的顶级分支,并创建一个新列表,其中包含该分支是否是叶子,该叶子,以及如果该分支还有其他两个分支,则第一个叶子和其余分支都是如此.

This loops over the original tree top-level branches and creates a new list containing if the branch was a leaf, that leaf, and if the branch had two other branches, then both the first leaf and the rest of the branches.

对不起,实际上第一次不好,现在应该修复它.

sorry, it wasn't good the first time actually, now it should be fixed.

仅因为我差点迷糊了自己. (cons (car e) (cdr e))看起来有点怪异,因为它与说e基本上相同.但是,我意识到nconc将破坏性地修改问题,因此必须采用这种方式(即,创建要串联的新cons单元,而不是重用旧的cons单元).

just because I almost got confused myself. (cons (car e) (cdr e)) looks a little weird because it is basically the same as saying just e. However, I realized that nconc will destructively modify the conses, so it has to be this way (i.e. create a new cons cell to be concatenated rather than reuse the old one).

哇...实际上,它必须是copy-list,因为它将以这种方式修改原始列表.

Wow... actually, it has to be copy-list, because it will modify the original list this way.

这篇关于扁平化Lisp中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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