Idris2/tests/chez/chez028/ExpressionParser.idr

56 lines
1.2 KiB
Idris
Raw Normal View History

module Main
import Control.Monad.Identity
import Control.Monad.Trans
import Data.Nat
import Data.String.Parser
import Data.String.Parser.Expression
%default partial
table : OperatorTable Nat
table =
2020-08-22 10:13:34 +03:00
[ [ Infix (token "^" $> power ) AssocRight]
, [ Infix (token "*" $> (*) ) AssocLeft ]
, [ Infix (token "+" $> (+) ) AssocLeft ]
]
table' : OperatorTable Integer
table' =
2020-08-22 10:13:34 +03:00
[ [ Infix (token "*" $> (*) ) AssocLeft
, Infix (token "/" $> div ) AssocLeft
]
2020-08-22 10:13:34 +03:00
, [ Infix (token "+" $> (+) ) AssocLeft
, Infix (token "-" $> (-) ) AssocLeft
]
]
mutual
term : Parser Nat
2020-08-22 10:13:34 +03:00
term = lexeme (natural <|> expr)
<?> "simple expression"
expr : Parser Nat
expr = buildExpressionParser Nat table term
mutual
term' : Parser Integer
2020-08-22 10:13:34 +03:00
term' = lexeme (integer <|> expr')
<?> "simple expression"
expr' : Parser Integer
expr' = buildExpressionParser Integer table' term'
2020-08-22 10:13:34 +03:00
run : Show a => Parser a -> String -> IO ()
run p s = case parse (p <* eos) s of
Left err => putStrLn err
2020-08-22 10:13:34 +03:00
Right (xs, _) => printLn xs
main : IO ()
2020-08-22 10:13:34 +03:00
main = do run natural "5678"
run integer "-3"
run expr "1+4^3^2^1"
run expr' "4 + 2 * 3"
run expr' "13-3+1*2-10/2"