Home > Back-end >  fold [IO Bool] with (&&) in Haskell?
fold [IO Bool] with (&&) in Haskell?

Time:02-18

For instance, we have:

flags :: [IO Bool]

What is the most concise way to fold flags with (&&)?

ie. To obtain the result if all flags (the elements of a list of True or False wrapped in IO) are True -> True, otherwise False

Please advise.

CodePudding user response:

Using Hoogle to search for Monad m => (a -> a -> a) -> [m a] -> m a didn't produce any results, but when I searched for Monad m => [m Bool] -> m Bool I found Control.Monad.Extra.andM:

-- | A version of 'and' lifted to a monad. Retains the short-circuiting behaviour.
andM :: Monad m => [m Bool] -> m Bool

which is exactly what's asked for.

CodePudding user response:

One possible solution is to import Control.Monad and

foldr (liftM2 (&&)) (Just True) flags
  • Related