Implement Applicative Parser

This commit is contained in:
Laborratte 5 2024-07-17 00:22:38 +02:00
parent bf4592540a
commit 3deaeee24a
Signed by: Laborratte5
GPG key ID: 3A30072E35202C02

View file

@ -1,6 +1,7 @@
module Parser where module Parser where
import qualified Lexer import qualified Lexer as L
import Control.Applicative as Applicative
type AST = Expr type AST = Expr
@ -18,3 +19,21 @@ data Factor = Integer Int
| Parantheses Expr | Parantheses Expr
| NegFactor Factor | NegFactor Factor
deriving Show 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)