Scala Parser Issues

后端 未结 2 1325
不知归路
不知归路 2021-02-06 12:52

I am having issues testing out the Scala Parser Combinator functionality for a simple Book DSL.

Firstly there is a book class:

case class Book (name:Stri         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-06 13:14

    When you use ~> or <~, you are discarding the element from which the arrow comes. For example:

    "book" ~> stringLit // discards "book"
    "book" ~> stringLit ~> "has" // discards "book" and then stringLit
    "book" ~> stringLit ~> "has" ~> "isbn" // discards everything except "isbn"
    "book" ~> stringLit ~> "has" ~> "isbn" ~> stringLit // discards everything but the last stringLit
    

    You could write it like this:

    def bookSpec: Parser[Book] = ("book" ~> stringLit <~ "has" <~ "isbn") ~ stringLit ^^ {
      case name ~ isbn => new Book(name,isbn) 
    }
    

提交回复
热议问题