Parsec: Consume all input

戏子无情 提交于 2019-12-08 16:00:53

问题


One common problem I have with Parsec is that it tends to ignore invalid input if it occurs in the "right" place.

As a concrete example, suppose we have integer :: Parser Int, and I write

expression = sepBy integer (char '+')

(Ignore whitespace issues for a moment.)

This correctly parses something like "123+456+789". However, if I feed it "123+456-789", it merrily ignores the illegal "-" character and the trailing part of the expression; I actually wanted an error message telling me about the invalid input, not just having it silently ignore that part.

I understand why this happens; what I'm not sure about is how to fix it. What is the general method for designing parsers that consume all supplied input and succeed only if all of it is a valid expression?


回答1:


It's actually pretty simple--just ensure it's followed by eof:

parse (expression <* eof) "<interactive>" "123+456-789"

eof matches the end of the input, even if the input is just a string and not a file.

Obviously, this only makes sense at the top level of your parser.



来源:https://stackoverflow.com/questions/16209278/parsec-consume-all-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!