I am trying to parse some text, but I can't understand how to parse a list of symbols separated by some separator, which may or may not occur also at the end of the list.
Example (numbers separated by spaces):
set A = 1 2 3 4 5;
set B =6 7 8 9;
set C = 10 11 12 ;
If I use sepBy
, after the last space I got an error because it expects another digit, even if I try to read also many whitespace
after the list. If I use endBy
, I got an error when the space is missing.
import Text.ParserCombinators.Parsec
main :: IO ()
main = do
let input = "set A = 1 2 3 4 5;\n" ++
"set B =6 7 8 9;\n" ++
"set C = 10 11 12 ;\n"
case parse parseInput "(unknown)" input of
Left msg ->
print msg
Right rss ->
mapM_ (\(n, vs) -> putStrLn (n ++ " = " ++ show vs)) rss
whitespace :: GenParser Char st Char
whitespace = oneOf " \t"
parseInput :: GenParser Char st [(String, [Int])]
parseInput = parseRow `endBy` newline
parseRow :: GenParser Char st (String, [Int])
parseRow = do
string "set"
many1 whitespace
name <- many1 alphaNum
many whitespace
string "="
many whitespace
values <- many1 digit `sepBy` many1 whitespace
many whitespace
string ";"
return (name, map read values)