diff --git a/coursework/part1/src/Lib.hs b/coursework/part1/src/Lib.hs index 48bd5ac..943d290 100644 --- a/coursework/part1/src/Lib.hs +++ b/coursework/part1/src/Lib.hs @@ -48,3 +48,39 @@ char c = satisfy (== c) digit :: Parser Char Char digit = satisfy isDigit + +skipSpaces :: Parser Char String +skipSpaces = many (char ' ') + +number :: Parser Char Int +number = skipSpaces *> (strToInt <$> some digit) + where + strToInt = foldl (\acc x -> acc * 10 + digitToInt x) 0 + +data Operation = Add | Sub | Mul | Div deriving Show + +operationToString :: Operation -> String +operationToString op = case op of + Add -> " + " + Sub -> " - " + Mul -> " * " + Div -> " / " + +operationToOperator :: Operation -> (Int -> Int -> Int) +operationToOperator op = case op of + Add -> (+) + Sub -> (-) + Mul -> (*) + Div -> div + + +operation :: Parser Char Operation +operation = skipSpaces *> ( + char '+' *> pure Add <|> + char '-' *> pure Sub <|> + char '*' *> pure Mul <|> + char '/' *> pure Div + ) + +expression :: Parser Char (Int, Operation, Int) +expression = (,,) <$> number <*> operation <*> number <* skipSpaces