Lisp中的Flatten Nests功能-需要帮助理解 [英] Flatten Nests Function in Lisp - need help understanding

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

问题描述

我一直在尝试找到一种方法来将嵌套列表压缩成可以返回原始列表的数字,但是遇到了一些麻烦.

I've been trying to find a way to condense nested lists into numbers that go back in the original list, but I having some trouble.

我一直在看这里提供的flatten函数(是如此广泛):

I've been looking at the flatten function (that is so widely available) which is given here:

(defun flatten (l)
  (cond
    ((null l) nil)
    ((atom l) (list l))
    (t (loop for a in l appending (flatten a)))))

我了解此示例是递归,但是它如何工作?它会检查元素是否为null或原子,但是如果元素属于这些条件,该怎么办?

I understand this example is recursion, but how does it work? It check if the element is null or an atom, but what does it do if the element falls into these conditions?

推荐答案

在我这一天中,我们写的是(mapcan #'g l),而不是(loop for a in l appending (g a)).等同于(apply #'append (mapcar #'g l)),或多或少:

In my day instead of (loop for a in l appending (g a)) we wrote (mapcan #'g l). Which is equivalent to (apply #'append (mapcar #'g l)), more or less:

(defun flatten (l) (if l (if (atom l) (list l) (mapcan #'flatten l))))

那么在这种情况下是什么意思?假设您呼叫(flatten (list 1 2 3 4 5)).列表中的每个原子都被包含在一个列表中-成为一个单例列表,例如(1) (2)等.然后将它们全部附加在一起,返回给我们……原始列表:

So what does it mean in this case? Imagine you call (flatten (list 1 2 3 4 5)). Each atom in your list gets enclosed in a list - becomes a singleton list, like (1) (2) etc. Then they all are appended together, giving us back ... the original list:

( 1 2 3 4 5 )

( (1) (2) (3) (4) (5) )

( 1 2 3 4 5 )

因此展平原子列表是一个id操作(在Common LISP中,这是#'identity).现在想象一下,展平其中包含原子的列表以及原子列表.同样,列表中的每个元素都被flatten转换,然后将它们全部附加在一起.就像我们刚刚看到的那样,原子列表保持不变.原子分别包含在列表中.因此,追加将使我们返回嵌套列表中现在处于两个级别的所有原子,这些原子现在已变平:

So flattening a list of atoms is an id operation (in Common LISP, that's #'identity). Now imagine flattening a list which has atoms in it, and also a list of atoms. Again, each element of the list gets transformed by flatten and then they are all appended together. A list of atoms stays as itself, as we just saw. Atoms get enclosed each in a list. So appending will give us back all the atoms that were on two levels in the nested list, now flattened:

( 11 12 (1 2 3 4) 13 )

( (11) (12) (1 2 3 4) (13) )

( 11 12 1 2 3 4 13 )

依次类推,以便进行更多级别的嵌套.

And so on and so forth, for more levels of nesting as well.

NIL s作为列表中的元素会造成问题. NIL是一个空列表,并且空列表不包含任何内容,因此不应提供任何内容.但是NIL也是一个原子.因此,我们对此进行了特殊处理,以将其包含在一个单例列表中-保持原样,以便在附加时将其消失.

NILs as elements in lists pose a problem. NIL is an empty list, and empty list contains nothing, so should not contribute anything. But NIL is also an atom. So we make a special case for it, to not enclose it in a singleton list - leave it as it is, so when appended, it'll just disappear.

这篇关于Lisp中的Flatten Nests功能-需要帮助理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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