使用ReadP解析字符串的多个实例

时间:2017-04-09 12:59:29

标签: parsing haskell text-parsing string-parsing

问题陈述:解析"AB"

中的字符串"ABCDFGABIJABGHA"

约束:使用ReadP

预期解决方案:(["AB","AB","AB"],"whatever is left")

尝试:

getAll :: ReadP a -> ReadP [a]
getAll p = many loop
  where
    loop = p <|> (get >> loop)

readP_to_S (getAll $ string "AB") "ABCDFGABIJABGHA"
[([],"ABCDFGABIJABGHA"),(["AB"],"CDFGABIJABGHA"),(["AB","AB"],"IJABGHA"),(["AB"],"IJABGHA"),(["AB","AB","AB"],"GHA"),(["AB","AB"],"GHA"),(["AB","AB"],"GHA"),(["AB"],"GHA")]

我希望最后一个州成为(["AB","AB","AB"],"GHA")。是否可以使用ReadP

执行相同的操作

1 个答案:

答案 0 :(得分:1)

问题在于您正在使用<|>进行对称选择。如果您希望解析器毫无例外地匹配所有p,请使用提供的左偏置选项:<++

getAll :: ReadP a -> ReadP [a]
getAll p = many loop
  where
    loop = p <++ (get >> loop)