Финальная функция для обработки строк
This commit is contained in:
@@ -61,10 +61,10 @@ data Operation = Add | Sub | Mul | Div deriving Show
|
|||||||
|
|
||||||
operationToString :: Operation -> String
|
operationToString :: Operation -> String
|
||||||
operationToString op = case op of
|
operationToString op = case op of
|
||||||
Add -> " + "
|
Add -> "+"
|
||||||
Sub -> " - "
|
Sub -> "-"
|
||||||
Mul -> " * "
|
Mul -> "*"
|
||||||
Div -> " / "
|
Div -> "/"
|
||||||
|
|
||||||
operationToOperator :: Operation -> (Int -> Int -> Int)
|
operationToOperator :: Operation -> (Int -> Int -> Int)
|
||||||
operationToOperator op = case op of
|
operationToOperator op = case op of
|
||||||
@@ -84,3 +84,19 @@ operation = skipSpaces *> (
|
|||||||
|
|
||||||
expression :: Parser Char (Int, Operation, Int)
|
expression :: Parser Char (Int, Operation, Int)
|
||||||
expression = (,,) <$> number <*> operation <*> number <* skipSpaces
|
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 ++ "\""
|
||||||
Reference in New Issue
Block a user