Full parser examples with parsec?

时光毁灭记忆、已成空白 提交于 2019-12-02 16:18:52

Hmm,

*Expr> parse expr "" "a(6)"
Right (FuncCall "a" [Number 6.0])

that part works for me after filling out the missing pieces.

Edit: I filled out the missing pieces by writing my own float parser, which could parse integer literals. The float parser from Text.Parsec.Token on the other hand, only parses literals with a fraction part or an exponent, so it failed parsing the "6".

However,

*Expr> parse expr "" "variable"
Left (line 1, column 9):
unexpected end of input
expecting "("

when call fails after having parsed an identifier, that part of the input is consumed, hence ident isn't tried, and the overall parse fails. You can a) make it try call in the choice list of expr, so that call fails without consuming input, or b) write a parser callOrIdent to use in expr, e.g.

callOrIdent = do
    name <- identifier
    liftM (FuncCall name) (parens $ commaSep expr) <|> return (Identifier name)

which avoids try and thus may perform better.

I wrote up a series of examples on how to parse Roman Numerals with parsec. It's pretty basic but you or other newcomers may find it useful:

https://github.com/russell91/roman

The book Write Yourself a Scheme in 48 Hours is an excellent, in depth overview and tutorial of Parsec's functionality. It walks you through everything with in depth examples, and by the end you've implemented a pretty significant portion of scheme in a parsec interpreter.

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