Scala combinator parser, what does >> mean?

前端 未结 2 457
北荒
北荒 2021-02-03 15:47

I am little bit confusing about \">>\" in scala. Daniel said in Scala parser combinators parsing xml? that it could be used to parameterize the parser base on result from previo

2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-03 16:07

    The method >> takes a function that is given the result of the parser and uses it to contruct a new parser. As stated, this can be used to parameterize a parser on the result of a previous parser.

    Example

    The following parser parses a line with n + 1 integer values. The first value n states the number of values to follow. This first integer is parsed and then the result of this parse is used to construct a parser that parses n further integers.

    Parser definition

    The following line assumes, that you can parse an integer with parseInt: Parser[Int]. It first parses an integer value n and then uses >> to parse n additional integers which form the result of the parser. So the initial n is not returned by the parser (though it's the size of the returned list).

    def intLine: Parser[Seq[Int]] = parseInt >> (n => repN(n,parseInt))
    

    Valid inputs

    1 42
    3 1 2 3
    0
    

    Invalid inputs

    0 1
    1
    3 42 42
    

提交回复
热议问题