2020-07-29 23:04:52 +03:00
|
|
|
module Main
|
|
|
|
|
|
|
|
import Control.Monad.Identity
|
|
|
|
import Control.Monad.Trans
|
|
|
|
|
|
|
|
import Data.Nat
|
|
|
|
import Data.String.Parser
|
2020-08-06 13:42:38 +03:00
|
|
|
import Data.String.Parser.Expression
|
2020-07-29 23:04:52 +03:00
|
|
|
|
|
|
|
%default partial
|
|
|
|
|
|
|
|
table : OperatorTable Nat
|
|
|
|
table =
|
|
|
|
[ [Infix (do token "^"; pure (power) ) AssocRight]
|
2020-08-10 14:25:46 +03:00
|
|
|
, [ Infix (do token "*"; pure (*) ) AssocLeft ]
|
|
|
|
, [ Infix (do token "+"; pure (+) ) AssocLeft ]
|
|
|
|
]
|
|
|
|
|
|
|
|
table' : OperatorTable Integer
|
|
|
|
table' =
|
|
|
|
[ [ Infix (do token "*"; pure (*) ) AssocLeft
|
|
|
|
, Infix (do token "/"; pure (div) ) AssocLeft
|
|
|
|
]
|
|
|
|
, [ Infix (do token "+"; pure (+) ) AssocLeft
|
|
|
|
, Infix (do token "-"; pure (-) ) AssocLeft
|
|
|
|
]
|
|
|
|
]
|
2020-07-29 23:04:52 +03:00
|
|
|
|
|
|
|
mutual
|
|
|
|
term : Parser Nat
|
|
|
|
term = (natural <|> expr) <* spaces
|
|
|
|
<?> "simple expression"
|
|
|
|
|
|
|
|
expr : Parser Nat
|
|
|
|
expr = buildExpressionParser Nat table term
|
|
|
|
|
2020-08-10 14:25:46 +03:00
|
|
|
mutual
|
|
|
|
term' : Parser Integer
|
|
|
|
term' = (integer <|> expr') <* spaces
|
|
|
|
<?> "simple expression"
|
|
|
|
|
|
|
|
expr' : Parser Integer
|
|
|
|
expr' = buildExpressionParser Integer table' term'
|
|
|
|
|
2020-07-29 23:04:52 +03:00
|
|
|
showRes : Show a => Either String (a, Int) -> IO ()
|
|
|
|
showRes res = case res of
|
|
|
|
Left err => putStrLn err
|
|
|
|
Right (xs, rem) => printLn xs
|
|
|
|
|
|
|
|
main : IO ()
|
|
|
|
main = do showRes (parse natural "5678")
|
2020-08-10 14:25:46 +03:00
|
|
|
showRes (parse integer "-3")
|
2020-07-29 23:04:52 +03:00
|
|
|
showRes (parse expr "1+4^3^2^1")
|
2020-08-10 14:25:46 +03:00
|
|
|
showRes (parse expr' "4 + 2 * 3")
|
|
|
|
showRes (parse expr' "13-3+1*2-10/2")
|