如何使用“缺点”,而不在计划产生嵌套的列表? [英] How to use 'cons' without generating nested lists in Scheme?

查看:142
本文介绍了如何使用“缺点”,而不在计划产生嵌套的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在试图产生存在两套内的子集的列表,我遇到的一个问题是劣势。一种处理过程,一个列表有一个名为结果并试图构建一个新的列表出来的结果汽车另一套的。到目前为止,与正确的元件产生的集,但它们都包含在一个尺寸中的 N 嵌套列表,其中N是嵌套的数目和元件的子集内的数为哪些我寻找。

While attempting to generate a list of subsets that exist within two sets, I am running into an issue with cons. A procedure takes in a list named result and attempts to construct a new list out of result and the car of another set. So far, the set is generated with the correct elements, but they are contained within a size N nested list, where N is the number of nestings and the number of elements within the subset for which I am searching.

如何申请劣势结果,而无需创建一个嵌套列表?

How can I apply cons with result without creating a nested list?

例如:

;These are two sets that I will be checking
(define s1 '(1 2 3 4))
(define s2 '(1 2 3))
;Result from running these lists through my procedure
(((() . 1) . 2) . 3)
;What I want to have generated
(1 2 3)

我需要能够调用(汽车名单)和接收 1 不是 ((()1)。2)

推荐答案

首先(((()1)2)。3)不是嵌套列表 - 它不是一个名单都没有。 (((()1)2)3)将是一个嵌套列表。 (((()1)2)。3)是一个点对的第一个元素也是一个点对。

First of all (((() . 1) . 2) . 3) is not a nested list - it's not a list at all. (((() 1) 2) 3) would be a nested list. (((() . 1) . 2) . 3) is a dotted pair whose first element is also a dotted pair.

所以现在来解释你看到的行为:在语言Lisp的家庭(缺点AB)创建一个包含一对 A ,因为它是 b CDR

So now to explain the behaviour you see: In the lisp family of languages (cons a b) creates a pair containing a as it's car and b as its cdr.

现在列表要么是空列表(())或者一对的 CDR 也是一个列表(在可能包含任何东西 - 如果这两个 CDR 是一个列表,该列表被称为嵌套列表)。

Now a list is either the empty list (()) or a pair whose cdr is also a list (the car might contain anything - if both the cdr and the car are a list, the list is called a nested list).

一对不是一个列表,称为点对。这个你正在创建这里,因为你调用利弊是什么与不是一个列表。第二个参数

A pair that is not a list is called a dotted pair. This what you're creating here because you're calling cons with a second argument which is not a list.

您不能使用劣势来追加到列表的末尾。如果需要追加到列表的末尾,你可以使用 CONCAT 用单元素列表的第二个参数。

You can not use cons to append to the end of the list. If you need to append to the end of a list, you can use concat with a single-element list as the second argument.

然而要注意追加到列表的末尾,是 O(N)操作,而在前面附加(使用利弊)是 O(1)运行,所以如果可能的话,你应该改变你的算法,因此只需要在前面追加。

Note however that appending to the end of a list, is an O(n) operation while appending at the front (using cons) is an O(1) operation, so if possible you should change your algorithm, so it only needs to append at the front.

这篇关于如何使用“缺点”,而不在计划产生嵌套的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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