【问题标题】:Filtering Nothing from a List with foldr/foldl使用 foldr/foldl 从列表中过滤任何内容
【发布时间】:2017-11-15 19:05:12
【问题描述】:

我正在尝试使用 List 折叠实现 catMaybes,但不知道应该如何开始。

我的总体思路是使用 foldl 并使用 case 来过滤 Nothing 和 Just。之后,相同的函数必须将找到的部分连接在一起,我的代码到目前为止看起来像这样:

{-# LANGUAGE LambdaCase #-}
catMaybes :: [Maybe a] -> [a]
catMaybes xs = foldl((++) \case Nothing -> []; Just y -> y) [] xs

编译时遇到很多错误... 我认为我需要朝着正确的方向努力来解决这个问题。感谢您的帮助!

【问题讨论】:

  • 这试图将(++) 应用于非列表\case ...,这没什么意义。我建议尝试foldr (\x rest -> case x of ...) []
  • \case Nothing -> []; Just y -> [y]也可以拼写为toList

标签: haskell maybe


【解决方案1】:
Just y -> y

如果这需要与[] 统一,那么你应该在函数类型签名中说[Maybe [a]]。那或者你的意思是Just y -> [y]

(++) \case Nothing -> []; Just y -> y

这只是句法上的废话。我想你想要 1. 函数组合 2. 第一个参数的部分应用:

\b -> (b ++) . \case Nothing -> []; Just y -> y

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    • 2016-09-04
    • 2011-08-28
    • 2015-01-08
    相关资源
    最近更新 更多