module Plutus.Contract.Util where

-- | A monadic version of 'loop', where the predicate returns 'Left' as a seed
--   for the next loop or 'Right' to abort the loop.
--
-- https://hackage.haskell.org/package/extra-1.6.15/docs/src/Control.Monad.Extra.html#loopM
loopM :: Monad m => (a -> m (Either a b)) -> a -> m b
loopM :: (a -> m (Either a b)) -> a -> m b
loopM a -> m (Either a b)
act a
x = do
    Either a b
res <- a -> m (Either a b)
act a
x
    case Either a b
res of
        Left a
x' -> (a -> m (Either a b)) -> a -> m b
forall (m :: * -> *) a b.
Monad m =>
(a -> m (Either a b)) -> a -> m b
loopM a -> m (Either a b)
act a
x'
        Right b
v -> b -> m b
forall (m :: * -> *) a. Monad m => a -> m a
return b
v

-- | Repeatedly evaluate the action until it yields 'Nothing',
--   then return the aggregated result.
foldMaybe
    :: Monad m
    => (a -> b -> b)
    -> b
    -> m (Maybe a)
    -> m b
foldMaybe :: (a -> b -> b) -> b -> m (Maybe a) -> m b
foldMaybe a -> b -> b
f b
b m (Maybe a)
con = (b -> m (Either b b)) -> b -> m b
forall (m :: * -> *) a b.
Monad m =>
(a -> m (Either a b)) -> a -> m b
loopM b -> m (Either b b)
go b
b where
    go :: b -> m (Either b b)
go b
b' = Either b b -> (a -> Either b b) -> Maybe a -> Either b b
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (b -> Either b b
forall a b. b -> Either a b
Right b
b') (b -> Either b b
forall a b. a -> Either a b
Left (b -> Either b b) -> (a -> b) -> a -> Either b b
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (a -> b -> b) -> b -> a -> b
forall a b c. (a -> b -> c) -> b -> a -> c
flip a -> b -> b
f b
b') (Maybe a -> Either b b) -> m (Maybe a) -> m (Either b b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> m (Maybe a)
con

-- | Monadic version of `<*`
finally :: Monad m => m a -> m b -> m a
finally :: m a -> m b -> m a
finally m a
a m b
b = do
    a
a' <- m a
a
    b
_ <- m b
b
    a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return a
a'

uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 :: (a -> b -> c -> d) -> (a, b, c) -> d
uncurry3 a -> b -> c -> d
f (a
a, b
b, c
c) = a -> b -> c -> d
f a
a  b
b c
c