2012-01-19 36 views
3

這是所有FParsec的最令人費解的組合子...有人可以舉一個在FParsec中使用chainl1的例子嗎?

http://www.quanttec.com/fparsec/reference/primitives.html#members.chainl1

...但對如何使用它的文件中,或據我所知,上的任何網頁沒有例子互聯網。我有一個似乎需要它的左遞歸解析,但對於我的生活,我無法弄清楚如何調用它或傳遞給它。

請幫助:)

+1

看看這個http://stackoverflow.com/questions/4559399/can-parser-combinators-be-made-efficient。這個問題和一些答案使用'chainl1'。 – pad

回答

2

我放在一起FParsec一個簡單的表達式解析器在年底this unrelated post。以下是使用chainl1爲解析器爲操作數和運算符生成鏈式運算符表達式的解析器。

(* fop : (double -> double -> double) -> (env -> double) -> (env -> double) -> env -> double *) 
let fop op fa fb env = fa env |> op <| fb env 
(* Parse single operators - return function taking two operands and giving the result *) 
let (addop : Parser<_,unit>) = 
    sym "+" >>% fop (+) 
    <|> (sym "-" >>% fop (-)) 
(* term, expr - chain of operators of a given precedence *) 
let term = chainl1 atom mulop 
let expr = chainl1 term addop 
相關問題