如何在Haskell中使用理解从嵌套列表中删除空列表

植物群

我刚开始学习Haskell,然后开始研究理解理解,这使我可以通过为更大的集合提供条件来形成子集。

我试图做出一个理解,该理解采用一个嵌套列表(包含其他整数列表),并从它们和所有空内部列表中删除所有正奇数。

testList= [-3]:[-5,8]:[[1,3,5,7,9],[],[4,6,8,10],[1,3,6,7,9],[],[1]]

removingOnlyPosOdds xxs = [ [x | x <-xs, not (odd x && x > 0 )] | xs <- xxs, [] /= xs ] 

testList 在对它应用理解功能之前,它看起来像:

[[-3],[-5,8],[1,3,5,7,9],[],[4,6,8,10],[1,3,6,7,9],[],[1]]

应用removingOnlyPosOddstestList之后

The outcome was 
[[-3],[-5,8],[],[4,6,8,10],[6],[]] 

所以我意识到"[] /= xs"在功能描述中是删除了已经存在的

"[]"testList内部列表但不是由我从内部列表中删除正奇数引起的新的。

为了删除这些以及明智的代码,下一步应该怎么做?

我希望它看起来像

[[-3],[-5,8],[4,6,8,10],[6]]

有没有一种方法可以一概而论地概括理解能力?

还是有另一种方法可以更好地处理事物的清除(例如,空的内部列表)并建立更具体的集合?

威廉·范昂塞姆

您可以添加一些额外的过滤,并防止通过let子句两次执行相同的列表理解,例如:

removingOnlyPosOdds xxs = [ ys | xs <- xxs, let ys = [x | x <-xs, not (odd x && x > 0 )], not (null ys)  ]

或者我们可以添加一些额外的过滤,例如:

removingOnlyPosOdds :: Integral i => [[i]] -> [[i]]
removingOnlyPosOdds = filter (not . null) . map (filter (\x -> not (odd x && x > 0)))

甚至更没有意义:

import Control.Monad(liftM2)

removingOnlyPosOdds :: Integral i => [[i]] -> [[i]]
removingOnlyPosOdds = filter (not . null) . map (filter (not . liftM2 (&&) odd (>0)))

例如:

Prelude> removingOnlyPosOdds [[-3],[-5,8],[1,3,5,7,9],[],[4,6,8,10],[1,3,6,7,9],[],[1]]
[[-3],[-5,8],[4,6,8,10],[6]]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章