代码之家  ›  专栏  ›  技术社区  ›  Saurabh Nanda

筛选第一个匹配的一元操作(不计算所有操作)?

  •  -1
  • Saurabh Nanda  · 技术社区  · 5 年前

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

    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)
    
    0 回复  |  直到 5 年前