Full parser examples with parsec?

后端 未结 3 1826
逝去的感伤
逝去的感伤 2021-01-30 23:15

I\'m trying to make a parser for a simple functional language, a bit like Caml, but I seem to be stuck with the simplest things.

So I\'d like to know if there are some m

相关标签:
3条回答
  • 2021-01-30 23:19

    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

    0 讨论(0)
  • 2021-01-30 23:33

    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.

    0 讨论(0)
  • 2021-01-30 23:44

    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.

    0 讨论(0)
提交回复
热议问题