Is it possible to use one of the parsing libraries (e.g. Parsec) for parsing something different than a String? And how would I do this?
For the sake of simplicity, let's assume the input is a list of ints [Int]. The task could be
- drop leading zeros
- parse the rest into the pattern
(S+L+)*, whereSis a number less than 10, andLis a number larger or equal to ten. - return a list of tuples
(Int,Int), wherefstis the product of theSandsndis the product of theLintegers
It would be great if someone could show how to write such a parser (or something similar).
Yes, as user5402 points out,
Parseccan parse any instance ofStream, including arbitrary lists. As there are no predefined token parsers (as there are for text) you have to roll your own, (myTokenbelow) using e.g. tokenPrimThe only thing I find a bit awkward is the handling of "source positions".
SourcePosis an abstract type (rather than a type class) and forces me to use its "filename/line/column" format, which feels a bit unnatural here.Anyway, here is the code (without the skipping of leading zeroes, for brevity)
Trying it all out:
Note the awkward line/column format in the error message
Of course one could write a function
sanitiseSourcePos :: SourcePos -> MyListPosition