Search code examples
haskellattoparsec

Haskell parse list of integers with Attoparsec


I need some help parsing a list of comma delimited integers from a file, when the list of integers can be any length. The string might look like "1,2,3,4,5,6,7,8,..." and the list I need made would be like [1,2,3,4,5,6,7,8,...].

The file format looks like:

0,0:1; -- minimum of 1 integer after the :
0,1:1,2;
0,2:5;
0,3:5,16,223,281; -- any amount of integers can follow the :
...

My parser currently only reads one integer, but it needs to start reading more. I can use takeTill to read all the numbers into a ByteString, but then I have to parse yet another string with the same problem of not knowing exactly how many numbers there can be:

parseTile :: Parser Tile
parseTile = do
  x <- decimal
  char ','
  y <- decimal
  char ':'
  --t <- takeTill (\x -> x == ';')
  t <- decimal
  char ';'
  return $ Tile x y t

I found this, but it doesn't help me because my file isn't a json file.


Solution

  • You can use sepBy and decimal:

    parseTile :: Parser Tile
    parseTile = do
      x <- decimal
      char ','
      y <- decimal
      char ':'
      t <- decimal `sepBy` (char ',')
      char ';'
      return $ Tile x y t