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+)*
, whereS
is a number less than 10, andL
is a number larger or equal to ten. - return a list of tuples
(Int,Int)
, wherefst
is the product of theS
andsnd
is the product of theL
integers
It would be great if someone could show how to write such a parser (or something similar).
Yes, as user5402 points out,
Parsec
can 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, (myToken
below) using e.g. tokenPrimThe only thing I find a bit awkward is the handling of "source positions".
SourcePos
is 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