haskell - 过滤第一个匹配的单子动作(不评估所有动作)?
问题描述
我正在编写的以下函数是否有标准/优化的实现(可能是不必要的):
filterFirstM :: (Monad m, Foldable t) => (a -> Bool) -> t m a -> m a
filterFirstM predicate actions = foldlM fn Nothing actions
where
fn memo action = case memo of
Just _ -> pure memo
Nothing -> do
x <- action
pure $ if predicate x then (Just x) else Nothing
示例用法:
filterFirstM (== 1) [pure 0 :: IO Int, pure 1, error "not evaluated"] == (pure 1)
解决方案
推荐阅读
- python - 将 N 个不同的向量排列到一个对象数组中 - 不是矩阵
- r - R闪亮:plotly_build中的错误:缺少参数“p”,没有默认值
- swift - 将标签的文本设置为 nil 或将其设置为“”有什么区别?
- ruby-on-rails - 未定义的方法“登录”#
- c# - 仅知道 PropertyInfo 从 Enum 获取属性
- c++ - C++ WinSock2 等到客户端发送数据
- python - 如何在windows上构建tensorflow自定义操作
- r - 有没有一种快速的方法可以将字符串中的罗马数字转换为 R 中的阿拉伯语?
- r - 如何纠正 ICdiffupperwidesIII 分析中缺失值 TRUE/FALSE 的错误
- apache-spark - 从 pyspark 数据框中的结构类型获取字段值