Created
December 16, 2023 00:41
-
-
Save presci/42740c3312a0a13da216123a87015e79 to your computer and use it in GitHub Desktop.
you need to consume all the whitespace after the match
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Notes https://www.cs.utoronto.ca/~trebla/CSCC24-2023-Summer/08-parsing.html#token | |
import Text.Parsec | |
import Text.Parsec.String (Parser) | |
-- Parsec parser for a single integer | |
integerParser :: Parser Int | |
integerParser = (read <$> many1 digit) <* many space | |
-- Parsec parser for a list of integers separated by spaces | |
integerListParser :: Parser [Int] | |
integerListParser = integerParser `sepBy` spaces | |
-- Parsec parser for two lists separated by '|' | |
listsParser :: Parser ([Int], [Int]) | |
listsParser = do | |
list1 <- integerListParser | |
char '|' <* many space | |
list2 <- integerListParser | |
return (list1, list2) | |
-- Parse function | |
parseLists :: String -> Either ParseError ([Int], [Int]) | |
parseLists input = parse listsParser "" input | |
main :: IO () | |
main = do | |
let input = "1 2 3 4 | 9 0 9 8" | |
result = parseLists input | |
case result of | |
Left err -> print err | |
Right (list1, list2) -> do | |
putStrLn "List 1:" | |
print list1 | |
putStrLn "List 2:" | |
print list2 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment