From 2e5df1862200510ddd997e00e4f1d6b25c52db13 Mon Sep 17 00:00:00 2001 From: Jaro Reinders Date: Mon, 10 Apr 2023 16:03:06 +0200 Subject: [PATCH] Add data dependent experiment --- experiments/DataDependent.hs | 43 ++++++++++++++++++++++++++++++++++++ gigaparsec.cabal | 11 ++++++--- 2 files changed, 51 insertions(+), 3 deletions(-) create mode 100644 experiments/DataDependent.hs diff --git a/experiments/DataDependent.hs b/experiments/DataDependent.hs new file mode 100644 index 0000000..6c904fd --- /dev/null +++ b/experiments/DataDependent.hs @@ -0,0 +1,43 @@ +{-# LANGUAGE DeriveFunctor #-} +import Control.Applicative +import Data.Char + +newtype Parser s a = Parser { parse :: String -> s -> [(a, String, s)] } deriving Functor + +instance Applicative (Parser s) where + pure x = Parser $ \xs s -> [(x, xs, s)] + Parser p <*> Parser q = Parser $ \xs s -> do + (f, xs', s') <- p xs s + (x, xs'', s'') <- q xs' s' + pure (f x, xs'', s'') + +instance Alternative (Parser s) where + empty = Parser $ \_ _ -> [] + Parser p <|> Parser q = Parser $ \xs s -> + p xs s ++ q xs s + +char :: Char -> Parser s Char +char c = Parser $ \xs s -> + case xs of + c' : xs' | c == c' -> [(c, xs', s)] + _ -> [] + +put :: Parser s' s -> Parser s a -> Parser s' a +put (Parser p) (Parser q) = Parser $ \xs s -> do + (s', xs', _) <- p xs s + (x, xs'', _) <- q xs' s' + pure (x, xs'', s) + +modify :: (s -> [s]) -> Parser s () +modify f = Parser $ \xs s -> [((), xs, s') | s' <- f s] + +dependentReplicate :: Parser s Int -> Parser Int a -> Parser s [a] +dependentReplicate p1 p2 = put p1 rest where + rest = (:) <$ modify (\s -> [s | s > 0]) <*> p2 <* modify (\s -> [s - 1]) <*> rest + <|> [] <$ modify (\s -> [s | s == 0]) + +digit :: Parser s Int +digit = asum [digitToInt <$> char (intToDigit i) | i <- [0..9]] + +main :: IO () +main = print $ parse (dependentReplicate digit (char '.')) "4...." () \ No newline at end of file diff --git a/gigaparsec.cabal b/gigaparsec.cabal index 08ec209..25491fe 100644 --- a/gigaparsec.cabal +++ b/gigaparsec.cabal @@ -20,8 +20,8 @@ description: I have also not put any effort in making this library performant yet. source-repository head - type: git - location: https://github.com/noughtmare/gigaparsec + type: git + location: https://github.com/noughtmare/gigaparsec common common build-depends: base >= 4.14 && <5 @@ -40,4 +40,9 @@ executable gigaparsec-examples import: common main-is: Main.hs hs-source-dirs: examples - build-depends: gigaparsec \ No newline at end of file + build-depends: gigaparsec + +executable gigaparsec-experiments-datadependent + import: common + main-is: DataDependent.hs + hs-source-dirs: experiments \ No newline at end of file