【问题标题】:Haskell filtering data constructor in nested lists嵌套列表中的 Haskell 过滤数据构造函数
【发布时间】:2018-02-12 23:58:59
【问题描述】:

我有以下自定义数据类型:

data Particle = Foo String | Goo String

通过以下调用:

func [[Foo "a"], [Goo "b", Foo "a"], [Goo "a"], [Foo "d"]]

函数定义为:

func :: [[Particle]] -> [[Particle]]

我想过滤粒子的嵌套列表,以便我的输出如下:

[[], [Goo "b"], [Foo "d"]]

为了用文字解释func在做什么,它看一下第一个列表中的第一个Particle,它被确定为Foo“a”。它从所有列表中删除 Foo "a",如果它碰巧在任何列表(包括第一个列表)中找到一个 Goo "a",它会完全破坏包含它的列表。

但我的输出似乎是错误的。我来了

[[Goo "a"], [Foo "d"]] 

我应该什么时候得到

[[], [Goo "b"], [Foo "d"]]

(这是因为Foo“a”从第一个和第二个列表中删除,Goo“a”销毁第三个列表,第四个列表保持不变,见下列表)

为了便于阅读,复制列表

    [[Foo "a"], [Goo "b", Foo "a"], [Goo "a"], [Foo "d"]]

有什么帮助吗?我知道 filter 和 elem 是必需的(我一直在使用它们,但无法获得正确的顺序),但我似乎无法正确实现。

编辑:已解决。我不得不在列表理解上投入更多时间。谢谢。

【问题讨论】:

标签: list haskell functional-programming


【解决方案1】:

这看起来像是列表推导的一个很好的例子,在本例中是一个嵌套的。

data Particle = Foo String | Goo String
  deriving (Eq, Show)

func :: [[Particle]] -> [[Particle]]
func []        = []
func xss@(x:_) = [[y | y <- ys, y /= badParticle] | ys <- xss, worseParticle `notElem` ys]
  where
  (badParticle: _) = x
  worseParticle    = case badParticle of
                     Foo s -> Goo s
                     Goo s -> undefined  -- what do you do in this case?

让我先分解理解,where 子句。

(badParticle: _) = x
-- this is equivalent to `badParticle = head x`

worseParticle    = case badParticle of
                   Foo s -> Goo s
                   Goo s -> undefined
-- Just some case matching to go Foo -> Goo

然后是列表推导本身。

[ [y | y <- ys, y /= badParticle]
  {- a list of every y from ys, where y is not the bad particle
     this is equivalent to `filter (/= badParticle) ys` -}
  | ys <- xss
  {- where ys draws from xss -}
  , worseParticle `notElem` ys
  {- and worseParticle is not an element of ys -}
]

Try it here

【讨论】:

  • 没关系,我想我想通了。再次感谢您的帮助,您的解释真的很有帮助!
猜你喜欢
  • 1970-01-01
  • 2018-07-22
  • 1970-01-01
  • 2017-05-09
  • 2022-01-22
  • 2011-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多