开发者

Return type of "|" in Scala's parser combinators

开发者 https://www.devze.com 2022-12-14 04:49 出处:网络
I was reading Bernie Pope\'s slides on \"Parser开发者_运维知识库 combinators in Scala\". He quotes the method signature type of the \"alternative\" combinator |:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消