From 62065753a52f66eb8234deb2e4d09f83d870080c Mon Sep 17 00:00:00 2001 From: Charles Date: Tue, 10 Mar 2020 16:10:34 +0100 Subject: Parser refactoring and replaced stdlib sqrt function with mySqrt --- src/parser.hs | 39 ++++++++++----------------------------- 1 file changed, 10 insertions(+), 29 deletions(-) (limited to 'src/parser.hs') diff --git a/src/parser.hs b/src/parser.hs index bfab053..d523001 100644 --- a/src/parser.hs +++ b/src/parser.hs @@ -40,34 +40,23 @@ instance Alternative Parser where where new_p s = p1 s <|> p2 s -charP :: Char -> Parser Char -charP x = Parser p - where p "" = Nothing - p (c:cs) = if c == x then Just (c, cs) - else Nothing - satisfy :: (Char -> Bool) -> Parser Char satisfy f = Parser p where p [] = Nothing p (c:cs) = if f c then Just (c, cs) else Nothing +charP :: Char -> Parser Char +charP c = satisfy (c ==) + digitsP :: Parser String digitsP = some (satisfy isDigit) -- at least one digit to avoid read exception spacesP :: Parser String spacesP = many (satisfy isSpace) -sepBy :: Parser a -> Parser b -> Parser [a] -sepBy x sep = many (sep *> x) - -prefixedIntP :: Parser Int -prefixedIntP = read <$> numStr - where numStr = ((:) <$> charP '-' <*> (spacesP *> digitsP)) - <|> (charP '+' *> spacesP *> digitsP) - -intP :: Parser Int -intP = prefixedIntP <|> (read <$> digitsP) +sepBy :: Parser b -> Parser a -> Parser [a] +sepBy sep x = many (sep *> x) naturalP :: Parser Int naturalP = read <$> digitsP @@ -76,13 +65,6 @@ floatPositiveP :: Parser Float floatPositiveP = (f <$> digitsP <*> charP '.' <*> digitsP) <|> (read <$> digitsP) where f pos dot dec = read $ pos ++ [dot] ++ dec -signP :: Parser Char -signP = charP '-' <|> charP '+' - -optionnal :: Parser a -> a -> Parser a -optionnal p placeholder = p <|> pure placeholder - - -- Equation parsers unsignedTermP :: Parser Term @@ -102,15 +84,14 @@ unsignedTermP = fullP <|> varExpP <|> varConstP <|> constP expP = spacesP *> charP '^' *> spacesP signedTermP :: Parser Term -signedTermP = signF <$> signP <*> (spacesP *> unsignedTermP) - where signF '-' (Term c e) = Term (-c) e +signedTermP = signF <$> signP <* spacesP <*> unsignedTermP + where signP = charP '-' <|> charP '+' + signF '-' (Term c e) = Term (-c) e signF _ t = t -firstTermP :: Parser Term -firstTermP = signedTermP <|> unsignedTermP - polynomialP :: Parser Polynomial -polynomialP = ((:) <$> firstTermP <*> (spacesP *> (sepBy signedTermP spacesP))) +polynomialP = (:) <$> firstTermP <* spacesP <*> (sepBy spacesP signedTermP) + where firstTermP = signedTermP <|> unsignedTermP equationP :: Parser Equation equationP = (\l r -> Equation l r) -- cgit