Skip to content

Instantly share code, notes, and snippets.

@SethTisue
Created July 22, 2014 04:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SethTisue/0a8cf256f9bcfc109755 to your computer and use it in GitHub Desktop.
Save SethTisue/0a8cf256f9bcfc109755 to your computer and use it in GitHub Desktop.
def parseProgram(s: String): Either[String, Program] = {
// use Stream so we don't keep parsing past the first error
val allLines: Stream[Either[String, Line]] =
s.split("""\n""")
.filter(_.nonEmpty)
.toStream
.map(parseLine)
sequence(allLines).right.map{goodLines =>
Program(goodLines.sortBy(_.number).toIndexedSeq)}
}
// returns the first Left, or all of the Rights
def sequence[A, B](xs: Stream[Either[A, B]]): Either[A, Stream[B]] =
xs.collectFirst{case Left(err) => err} match {
case Some(err) =>
Left(err)
case None =>
Right(xs.collect{case Right(x) => x})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment