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

97 views Asked by At

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

There are 0 answers