【问题标题】:How to remove Empty Lists from a nested List using comprehension in Haskell如何使用 Haskell 中的理解从嵌套列表中删除空列表
【发布时间】:2019-04-13 04:14:19
【问题描述】:

我刚开始学习 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]]

有没有一种方法可以概括理解以一次性完成?

或者是否有另一种方法可以更好地处理删除事物(例如空的内部列表)并制作更指定的集合?

【问题讨论】:

    标签: haskell


    【解决方案1】:

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

    removingOnlyPosOdds xxs = [ ys | xs &lt;- xxs, <b>let ys =</b> [x | x &lt;-xs, not (odd x &amp;&amp; x &gt; 0 )], <b>not (null ys)</b>  ]

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

    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]]
    

    【讨论】:

      猜你喜欢
      • 2021-08-21
      • 1970-01-01
      • 2019-08-20
      • 2019-02-27
      • 1970-01-01
      • 2022-06-17
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      相关资源
      最近更新 更多