module MonusWeightedSearch.Examples.Parsing where
import Control.Applicative
import Control.Monad.Heap
import Control.Monad.State
import Data.Monus.Prob
import Control.Monad.Writer
import Control.Monad (guard)
type Parser a = StateT [a] (Heap Prob)
eof :: Parser a ()
eof :: forall a. Parser a ()
eof = ([a] -> Heap Prob ((), [a])) -> StateT [a] (Heap Prob) ()
forall s (m :: Type -> Type) a. (s -> m (a, s)) -> StateT s m a
StateT \case
[] -> ((), [a]) -> Heap Prob ((), [a])
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure ((), [])
[a]
_ -> Heap Prob ((), [a])
forall (f :: Type -> Type) a. Alternative f => f a
empty
anyChar :: Parser a a
anyChar :: forall a. Parser a a
anyChar = ([a] -> Heap Prob (a, [a])) -> StateT [a] (Heap Prob) a
forall s (m :: Type -> Type) a. (s -> m (a, s)) -> StateT s m a
StateT \case
(a
x:[a]
xs) -> (a, [a]) -> Heap Prob (a, [a])
forall (f :: Type -> Type) a. Applicative f => a -> f a
pure (a
x, [a]
xs)
[] -> Heap Prob (a, [a])
forall (f :: Type -> Type) a. Alternative f => f a
empty
satisfy :: (b -> Bool) -> Parser a b -> Parser a b
satisfy :: forall b a. (b -> Bool) -> Parser a b -> Parser a b
satisfy b -> Bool
p Parser a b
xs = do
b
x <- Parser a b
xs
Bool -> StateT [a] (Heap Prob) ()
forall (f :: Type -> Type). Alternative f => Bool -> f ()
guard (b -> Bool
p b
x)
pure b
x
condition :: (b -> Prob) -> Parser a b -> Parser a b
condition :: forall b a. (b -> Prob) -> Parser a b -> Parser a b
condition b -> Prob
c Parser a b
xs = do
b
x <- Parser a b
xs
Prob -> StateT [a] (Heap Prob) ()
forall w (m :: Type -> Type). MonadWriter w m => w -> m ()
tell (b -> Prob
c b
x)
pure b
x
parse :: Parser a b -> [a] -> [(b, Prob)]
parse :: forall a b. Parser a b -> [a] -> [(b, Prob)]
parse Parser a b
p [a]
xs = Heap Prob b -> [(b, Prob)]
forall w a. Monus w => Heap w a -> [(a, w)]
search (Parser a b -> [a] -> Heap Prob b
forall (m :: Type -> Type) s a. Monad m => StateT s m a -> s -> m a
evalStateT (Parser a b
p Parser a b -> StateT [a] (Heap Prob) () -> Parser a b
forall (f :: Type -> Type) a b. Applicative f => f a -> f b -> f a
<* StateT [a] (Heap Prob) ()
forall a. Parser a ()
eof) [a]
xs)