Filter for first matching monadic action (without evaluating all actions)?

≡放荡痞女 提交于 2020-01-25 06:40:08

问题


Is there a standard / optimized implementation of the following function that I'm writing (probably unnecessarily):

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

Sample usage:

filterFirstM (== 1) [pure 0 :: IO Int, pure 1, error "not evaluated"] == (pure 1)

来源:https://stackoverflow.com/questions/59798509/filter-for-first-matching-monadic-action-without-evaluating-all-actions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!