Return type of "|" in Scala's parser combinators
I was reading Bernie Pope's slides on "Parser开发者_运维知识库 combinators in Scala". He quotes the method signature type of the "alternative" combinator |
:
def | [U >: T](q: => Parser[U]): Parser[U]
and asks, "Homework: why doesn’t | have this type instead?"
def | [U](q: => Parser[U]): Parser[Either[T,U]]
case class Stooge(name: String)
val moe: Parser[String] = "Moe"
val larry: Parser[String] = "Larry"
val curly: Parser[String] = "Curly"
val shemp: Parser[String] = "Shemp"
val stooge: Parser[Stooge] = (moe | larry | curly | shemp) ^^ { s => Stooge(s) }
Now, imagine the code you would have to write instead of { s => Stooge(s) }
if you were working with an s: Either[Either[Either[String,String],String],String]
instead of a s: String
.
精彩评论