Matt R
Matt R

Reputation: 10523

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]]

Upvotes: 2

Views: 480

Answers (1)

Mitch Blevins
Mitch Blevins

Reputation: 13196

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.

Upvotes: 1

Related Questions