Full parser examples with parsec?

后端 未结 3 1825
逝去的感伤
逝去的感伤 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: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.

提交回复
热议问题