Финальная функция для обработки строк

This commit is contained in:
2024-12-08 19:45:21 +03:00
parent 70d1742368
commit 1a45ec2330

View File

@@ -61,10 +61,10 @@ data Operation = Add | Sub | Mul | Div deriving Show
operationToString :: Operation -> String
operationToString op = case op of
Add -> " + "
Sub -> " - "
Mul -> " * "
Div -> " / "
Add -> "+"
Sub -> "-"
Mul -> "*"
Div -> "/"
operationToOperator :: Operation -> (Int -> Int -> Int)
operationToOperator op = case op of
@@ -84,3 +84,19 @@ operation = skipSpaces *> (
expression :: Parser Char (Int, Operation, Int)
expression = (,,) <$> number <*> operation <*> number <* skipSpaces
calculateExpression :: (Int, Operation, Int) -> Int
calculateExpression (a, op, b) = (operationToOperator op) a b
processExpression :: String -> String
processExpression s = case runParser expression s of
Nothing -> err
Just (cs, (a, op, b)) -> case cs of
[] ->
show a ++ " " ++
operationToString op ++ " " ++
show b ++ " = " ++
show (calculateExpression (a, op, b))
_ -> err
where
err = error $ "Unable to parse the following expression: \"" ++ s ++ "\""