module Prolog.Programming.Mutation (findFirstAliveMutation) where

import Control.Monad.Extra (firstJustM)
import Language.Prolog (ProgramClause)
import Prolog.Programming.Mutation.Types (Mutant (..), Mutation)

findFirstAliveMutation
  :: ([ProgramClause] -> IO Bool)
  -> [Mutant]
  -> IO (Maybe Mutation)
findFirstAliveMutation :: ([ProgramClause] -> IO Bool) -> [Mutant] -> IO (Maybe Mutation)
findFirstAliveMutation [ProgramClause] -> IO Bool
check = (Mutant -> IO (Maybe Mutation)) -> [Mutant] -> IO (Maybe Mutation)
forall (m :: * -> *) a b.
Monad m =>
(a -> m (Maybe b)) -> [a] -> m (Maybe b)
firstJustM ((Mutant -> IO (Maybe Mutation))
 -> [Mutant] -> IO (Maybe Mutation))
-> (Mutant -> IO (Maybe Mutation))
-> [Mutant]
-> IO (Maybe Mutation)
forall a b. (a -> b) -> a -> b
$ \(Mutant [ProgramClause]
mp Mutation
m) -> do
  res <- [ProgramClause] -> IO Bool
check [ProgramClause]
mp
  case res of
    Bool
False -> Maybe Mutation -> IO (Maybe Mutation)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Maybe Mutation
forall a. Maybe a
Nothing
    Bool
True -> Maybe Mutation -> IO (Maybe Mutation)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Maybe Mutation -> IO (Maybe Mutation))
-> Maybe Mutation -> IO (Maybe Mutation)
forall a b. (a -> b) -> a -> b
$ Mutation -> Maybe Mutation
forall a. a -> Maybe a
Just Mutation
m