简体   繁体   English

FParsec组合器转Parser <char,_> 直到Parser <string,_> ?

[英]FParsec combinator to turn Parser<char,_> until Parser<string,_>?

I'm certain there's a really simple answer to this, but I've been staring at this all day and I can't figure it out. 我确信这有一个非常简单的答案,但我一整天都在盯着这个,我无法弄明白。

As per the tutorial, I'm implementing a JSON parser. 根据教程,我正在实现一个JSON解析器。 To challenge myself, I'm implementing the number parser myself. 为了挑战自己,我自己实现了number解析器。

This is what I got so far: 这是我到目前为止所得到的:

let jnumber =
    let neg = stringReturn "-" -1 <|> preturn 1
    let digit = satisfy (isDigit)
    let digit19 = satisfy (fun c -> isDigit c && c <> '0')
    let digits = many1 digit
    let ``int`` =
        digit
        <|> (many1Satisfy2 (fun c -> isDigit c && c <> '0') isDigit)

The trouble is that digit is a Parser<char,_> , whereas the second option for int is a Parser<string,_> . 问题是digitParser<char,_> ,而int的第二个选项是Parser<string,_> Would I normally just use a combinator to turn digit into a Parser<char,_> , or is there something else I should do? 我通常只会使用组合器将digit转换为Parser<char,_> ,还是我还应该做些什么呢?

The |>> operator is what you're looking for. |>>运算符是您正在寻找的。 I quote the FParsec reference : 我引用FParsec参考

val (|>>): Parser<'a,'u> -> ('a -> 'b) -> Parser<'b,'u> 

The parser p |>> f applies the parser p and returns the result of the function application fx, where x is the result returned by p. 解析器p | >> f应用解析器p并返回函数应用程序fx的结果,其中x是p返回的结果。

p |>> f is an optimized implementation of p >>= fun x -> preturn (fx). p | >> f是p >> = fun x - > preturn(fx)的优化实现。

For example: 例如:

let jnumber =
    let neg = stringReturn "-" -1 <|> preturn 1
    let digit = satisfy (isDigit)
    let digit19 = satisfy (fun c -> isDigit c && c <> '0')
    let digits = many1 digit
    (digit |>> string) (* The operator is used here *)
    <|> (many1Satisfy2 (fun c -> isDigit c && c <> '0') isDigit)

You may want to read FParsec tutorial on parsing JSON which uses this operator quite intensively. 您可能希望阅读解析JSON的FParsec教程,教程非常密集地使用此运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM