Created
July 22, 2014 04:43
-
-
Save SethTisue/0a8cf256f9bcfc109755 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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