1

我正在编写的以下函数是否有标准/优化的实现(可能是不必要的):

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)
4

0 回答 0