Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Created March 3, 2014 19:12
Show Gist options
  • Save izmailoff/9332412 to your computer and use it in GitHub Desktop.
Save izmailoff/9332412 to your computer and use it in GitHub Desktop.
case class Transformer[From, To](input: List[From], f: From => To) {
import scala.util.{Try, Success, Failure}
lazy val transformedWithIndex: List[(Try[To], Int)] =
input map { l => Try ( f(l) ) } zipWithIndex
def failuresWithIndex =
transformedWithIndex.filter { case (v, i) => v.isFailure }
lazy val failuresExist: Boolean =
! failuresWithIndex.isEmpty
def successfulOnly: List[To] =
for {
(e, _) <- transformedWithIndex
value <- e.toOption
} yield value
}
val lines = List("12", "13", "13a", "14", "foo")
val res = Transformer(lines, (l: String) => l.toInt)
println("FAILURES EXIST?: " + res.failuresExist)
println("PARSED LINES WITH INDEX: " + res.transformedWithIndex)
println("SUCCESSFUL ONLY: " + res.successfulOnly)
/*
Prints:
FAILURES EXIST?: true
PARSED LINES WITH INDEX: List((Success(12),0), (Success(13),1), (Failure(java.lang.NumberFormatException: For input string: "13a"),2), (Success(14),3), (Failure(java.lang.NumberFormatException: For input string: "foo"),4))
SUCCESSFUL ONLY: List(12, 13, 14)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment