是的,正如 user5402 指出的那样,Parsec 可以解析Stream 的任何实例,包括任意列表。由于没有预定义的令牌解析器(如文本一样),您必须自己滚动,(myToken 下面)使用例如tokenPrim
我觉得唯一有点尴尬的是“源位置”的处理。 SourcePos 是一种抽象类型(而不是类型类),并迫使我使用它的“文件名/行/列”格式,这在这里感觉有点不自然。
无论如何,这是代码(为简洁起见,没有跳过前导零)
import Text.Parsec
myToken :: (Show a) => (a -> Bool) -> Parsec [a] () a
myToken test = tokenPrim show incPos $ justIf test where
incPos pos _ _ = incSourceColumn pos 1
justIf test x = if (test x) then Just x else Nothing
small = myToken (< 10)
large = myToken (>= 10)
smallLargePattern = do
smallints <- many1 small
largeints <- many1 large
let prod = foldl1 (*)
return (prod smallints, prod largeints)
myIntListParser :: Parsec [Int] () [(Int,Int)]
myIntListParser = many smallLargePattern
testMe :: [Int] -> [(Int, Int)]
testMe xs = case parse myIntListParser "your list" xs of
Left err -> error $ show err
Right result -> result
试一试:
*Main> testMe [1,2,55,33,3,5,99]
[(2,1815),(15,99)]
*Main> testMe [1,2,55,33,3,5,99,1]
*** Exception: "your list" (line 1, column 9):
unexpected end of input
注意错误消息中尴尬的行/列格式
当然可以写一个函数sanitiseSourcePos :: SourcePos -> MyListPosition