From 0888ae35770f9d3d269bb2345db016137dea7b92 Mon Sep 17 00:00:00 2001 From: Mart Lubbers Date: Mon, 28 Jan 2019 15:42:31 +0100 Subject: [PATCH] parserparser --- parserParser/test.icl | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/parserParser/test.icl b/parserParser/test.icl index 26a91d5..fb2eafa 100644 --- a/parserParser/test.icl +++ b/parserParser/test.icl @@ -14,38 +14,38 @@ import Text.Parsers.Simple.Core :: In a b = (:.) infix 0 a b :: Gram -// = Def (Gram -> In Gram Gram) -// | Def2 ((Gram,Gram) -> In (Gram, Gram) Gram) = Lit String | Int | (-.) infixr 2 Gram Gram | (|.) infixl 1 Gram Gram | *! Gram + | ?! Gram +Lits = foldr1 (|.) o map Lit +foldr1 f [x:xs] = foldr f x xs :: Gast = INT Int | LIT String | BIN Gast Gast + | OPT (Maybe Gast) | MANY [Gast] parseFromGram :: Gram -> Parser String Gast parseFromGram Int = INT o toInt <$> pSatisfy (\s->toString (toInt s) == s) parseFromGram (Lit i) = LIT <$> pSatisfy ((==)i) +parseFromGram (?! g) = OPT <$> optional (parseFromGram g) parseFromGram (*! g) = MANY <$> many (parseFromGram g) parseFromGram (a -. b) = BIN <$> parseFromGram a <*> parseFromGram b parseFromGram (a |. b) = parseFromGram a <|> parseFromGram b //Start = runParser (parseFromGram gram) [".","."] -Start = printeval <$> parse (parseFromGram gram) ["4","-","2","-","1"] +Start = printeval <$> parse (parseFromGram gram) ["4","*","2","*","1","*","(","3","^","3","^","3",")"] where gram = let lit = Lit "(" -. expr -. Lit ")" |. Int - pow = lit -. Lit "^" -. pow - |. lit - fac = pow -. *! (Lit "*" -. pow) - |. pow - expr = fac -. *! (Lit "-" -. fac) - |. fac + pow = lit -. ?! (Lit "^" -. pow) + fac = pow -. *! (Lits ["*","/"] -. pow) + expr = fac -. *! (Lits ["+","-","%"] -. fac) in expr printeval a = (eval a, print a) @@ -54,6 +54,8 @@ where eval (BIN (LIT "(") (BIN e (LIT ")"))) = eval e eval (INT i) = Just i eval (LIT _) = Nothing + eval (BIN l (OPT Nothing)) = eval l + eval (BIN l (OPT (Just a))) = eval (BIN l a) //Right associative operators eval (BIN l (BIN (LIT op) r)) = op2op op <*> eval l <*> eval r //Left associative operators @@ -66,6 +68,8 @@ where print (BIN (LIT "(") (BIN e (LIT ")"))) = "(" +++ print e +++ ")" print (INT i) = toString i print (LIT l) = l + print (BIN l (OPT Nothing)) = print l + print (BIN l (OPT (Just a))) = print (BIN l a) //Right associative operators print (BIN l (BIN (LIT op) r)) = "(" +++ print l +++ op +++ print r +++ ")" //Left associative operators @@ -77,6 +81,8 @@ where op2op "+" = Just (+) op2op "-" = Just (-) op2op "*" = Just (*) + op2op "/" = Just (/) + op2op "%" = Just (rem) op2op "^" = Just (^) op2op _ = Nothing -- 2.20.1