'Breaking the loop

I have the following code sample:

data Smth = A | B

data MyError = MkMyError

data MyState = MkMyState

run :: [Smth] -> Either MyError (Maybe Integer)
run param =
  evalState
    ( foldM
        ( \acc a -> do
            res <- go a
            case res of
              Right (Just _) -> undefined -- I want to break here when Right value is Just
              _ -> return (acc >> res)
        )
        (Right Nothing)
        param
    )
    MkMyState
  where
    go :: Smth -> State MyState (Either MyError (Maybe Integer))
    go = undefined

I have list of Smth that are processed sequentially and they process a result based on state in the State monad and the Smth value.

I want to break in the run when the go results in MyError (left value of the Either). This works with the code snippet using the >> operator.

However, I want to also have the possibility to break folding when the go function results in Right (Just _) (There is a comment on the line).

Question

How to break the following loop when I get the Just value? I want to break the loop in 2 cases:

  • in case of error - go resulting in Left value
  • in case of Just value - go resulting in Right (Just _) value. This is some kind of flipped behaviour of the Maybe monad and the >> operator. I don't want to break on Nothing, but on Just.

How could this be composed?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source