问题陈述:解析"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
?
答案 0 :(得分:1)
问题在于您正在使用<|>
进行对称选择。如果您希望解析器毫无例外地匹配所有p
,请使用提供的左偏置选项:<++
。
getAll :: ReadP a -> ReadP [a]
getAll p = many loop
where
loop = p <++ (get >> loop)