From 3deaeee24a9a56f8368f52e40d8c1e6c045cbd4e Mon Sep 17 00:00:00 2001 From: Laborratte5 Date: Wed, 17 Jul 2024 00:22:38 +0200 Subject: [PATCH] Implement Applicative Parser --- app/Parser.hs | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/app/Parser.hs b/app/Parser.hs index 3e981e8..5dee86d 100644 --- a/app/Parser.hs +++ b/app/Parser.hs @@ -1,6 +1,7 @@ module Parser where -import qualified Lexer +import qualified Lexer as L +import Control.Applicative as Applicative type AST = Expr @@ -18,3 +19,21 @@ data Factor = Integer Int | Parantheses Expr | NegFactor Factor deriving Show + +type Tokens = [L.Token] +newtype Parser a = Parser { + runParser :: Tokens -> Maybe (Tokens, a) +} + +instance Functor Parser where + fmap f (Parser p) = Parser $ \input -> case p input of + Nothing -> Nothing + Just (rest, a) -> Just (rest, f a) + +instance Applicative Parser where + pure x = Parser $ \input -> Just (input, x) + (<*>) (Parser fParser) (Parser a) = Parser $ \input -> case fParser input of + Nothing -> Nothing + Just (rest, f) -> case a rest of + Nothing -> Nothing + Just (rest', x) -> Just (rest', f x)