【问题标题】:Filter over [Maybe a] and discard Nothing values过滤 [Maybe a] 并丢弃 Nothing 值
【发布时间】:2021-02-03 01:31:19
【问题描述】:

对于Maybe a的列表,如何过滤只取列表中不是Nothing的元素?

-- input
pas = [Just 3, Just 1, Just 5, Just 9, Nothing, Just 10, Nothing] :: [Maybe Int]

-- expected output
new_pas = [3, 1, 5, 9, 10]

我尝试过使用map 的不同方式并查看了mapMaybe,但找不到合适的组合。

【问题讨论】:

  • map 本身无法过滤。 concat . map (\case Nothing -> [] ; Just x -> [x]) 会。 (当然,你的列表理解答案表明用 LC 写得更好)。

标签: list haskell filter map-function maybe


【解决方案1】:

在输入问题时,我找到了答案,而且实际上很简单:

new_pas = [pa | Just pa <- pas]
-- [3, 1, 5, 9, 10]

把它放在这里供其他人在谷歌上搜索相同的问题。

【讨论】:

    【解决方案2】:

    除了您找到的简单列表推导外,还有一个库函数:catMaybes

    请注意,您不仅可以搜索 Hoogle 来搜索名称,还可以搜索类型签名——这在许多情况下都非常有用。在此处输入[Maybe a] -&gt; [a] 会立即为您提供catMaybes。 (忏悔:我忘记了函数的名称,但知道它存在,刚刚找到它!)

    【讨论】:

      【解决方案3】:

      Your way with pattern-matching in list comprehension 很不错。然而,我也喜欢你提到的Data.Maybe.mapMaybe 的方式(注意它只是this answer 中Robin Zigmond 所说的Data.Maybe.catMaybe 下的一行)可以在这里使用:

      unwrapJusts :: [Maybe a] -> [a]
      unwrapJusts = mapMaybe id
      

      你的例子:

      GHCi> unwrapJusts [Just 3, Just 1, Just 5, Just 9, Nothing, Just 10, Nothing]
      [3,1,5,9,10]
      

      这个想法相当简单:当遍历列表mapMaybe id 时,会抛出所有Nothings(即id Nothings)并将Just xs 变成xs。

      【讨论】:

        猜你喜欢
        • 2021-12-24
        • 2018-11-14
        • 1970-01-01
        • 1970-01-01
        • 2016-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-21
        相关资源
        最近更新 更多