简体   繁体   English

Haskell 使用数据构造函数过滤嵌套列表

[英]Haskell filtering a nested list with data constructors

Let's say I have the following data type假设我有以下数据类型

data Number = Positive Integer | Negative Integer
     deriving (Eq, Show)

I have a function definition of (NOTE THAT I CANNOT CHANGE THIS DEFINITION, OR WORK AROUND IT IN ANY WAY. I have to work with the nested list and modify it in some way)我有一个函数定义(注意我不能改变这个定义,或者以任何方式绕过它。我必须使用嵌套列表并以某种方式修改它)

removePos :: [[Number]] -> [[Number]]

So we have a nested list of Number.所以我们有一个嵌套的 Number 列表。 An example would be一个例子是

[[Positive 1, Negative 1], [Positive 2, Negative 2, Positive 1], [Positive 1]]

How can I write removePos so that it removes all lists in the nested list that contain Positive x, where x is A SPECIFIC Integer?如何编写 removePos 以删除嵌套列表中包含正 x 的所有列表,其中 x 是特定整数? The function is essentially looking at the first element in the first list, if it is Positive then remove all lists that contain Positive x.该函数本质上是查看第一个列表中的第一个元素,如果它是 Positive,则删除所有包含 Positive x 的列表。

Essentially, if we took a look at the example above, the output would be本质上,如果我们看一下上面的例子,输出将是

[[]]

Note that the user performs the following function call注意用户执行以下函数调用

removePos [[Positive 1, Negative 1], [Positive 2, Negative 2, Positive 1], [Positive 1]]

Since each list in the nested list above contains Positive 1, the output is simply an empty nested list (All lists with Positive x are removed).由于上面嵌套列表中的每个列表都包含正值 1,因此输出只是一个空的嵌套列表(删除所有带有正值 x 的列表)。 However, if the first element in the first list was Positive 10, the output would be但是,如果第一个列表中的第一个元素是正 10,则输出将是

[[Positive 2, Negative 2, Positive 1], [Positive 1]]

(Because the first list would have [Positive 10, Negative 1], which would get removed) (因为第一个列表会有 [Positive 10, Negative 1],这将被删除)

Any ideas?有任何想法吗?

EDIT:编辑:

For further examples, lets say I have a basket with bowls of fruits in it.对于进一步的例子,假设我有一个篮子,里面装着几碗水果。 The basket is the nested list, the bowls are lists within it.篮子是嵌套列表,碗是其中的列表。 Now, I take a look in the basket.现在,我在篮子里看看。 I check the first bowl.我检查了第一碗。 I look at the first fruit in the bowl, and determine that I don't want to eat that fruit from any of the bowls.我看着碗里的第一个水果,确定我不想吃任何碗里的水果。 So I throw out all bowls that contain that fruit, and give you back your basket.所以我扔掉所有盛着水果的碗,把篮子还给你。

One way is pattern matching on the nested list to peek at the first element of the first list to figure out what you need to filter:一种方法是在嵌套列表上进行模式匹配以查看第一个列表的第一个元素以找出您需要过滤的内容:

-- Note you could give this the more general type Eq a => [[a]] -> [[a]]
-- (as well as a more appropriate name)
removePos :: [[Number]] -> [[Number]]
removePos [] = [] -- Empty list case.
removePos xss@[[]:_] = xss -- If the first inner list is empty,
                           -- return the whole thing unchanged
removePos ((x:_):xss) = filter (notElem x) xss

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM