Skip to content

Instantly share code, notes, and snippets.

@markhibberd
Created January 3, 2014 10:38
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 markhibberd/8235979 to your computer and use it in GitHub Desktop.
Save markhibberd/8235979 to your computer and use it in GitHub Desktop.
scala> def all[F[_]: Applicative, A](s: String, parsers: List[String => F[A]]): F[List[A]] = parsers.traverse(p => p(s))
all: [F[_], A](s: String, parsers: List[String => F[A]])(implicit evidence$1: scalaz.Applicative[F])F[List[A]]
scala> def toInt(s: String): String \/ Int = \/.fromTryCatch(s.toInt).leftMap(_.getMessage)
toInt: (s: String)scalaz.\/[String,Int]
scala> def one: String => (List[String] \/ Int) = s => toIntE(s).leftMap(List(_))
one: String => scalaz.\/[List[String],Int]
scala> def two: String => (List[String] \/ Int) = s => toIntE(s.take(2)).leftMap(List(_))
two: String => scalaz.\/[List[String],Int]
scala> def three: String => (List[String] \/ Int) = s => toIntE(s.drop(2)).leftMap(List(_))
three: String => scalaz.\/[List[String],Int]
scala> all[({ type l[a] = List[String] \/ a })#l, Int]("1234", List(one, two, three))
res11: scalaz.\/[List[String],List[Int]] = \/-(List(1234, 12, 34))
scala> all[({ type l[a] = List[String] \/ a })#l, Int]("asfasf", List(one, two, three))
res12: scalaz.\/[List[String],List[Int]] = -\/(List(For input string: "asfasf"))
scala> def oneV = one.map(_.validation)
oneV: String => scalaz.Validation[List[String],Int]
scala> def twoV = two.map(_.validation)
twoV: String => scalaz.Validation[List[String],Int]
scala> def threeV = three.map(_.validation)
threeV: String => scalaz.Validation[List[String],Int]
scala> all[({ type l[a] = Validation[List[String], a] })#l, Int]("1234", List(oneV, twoV, threeV))
res13: scalaz.Validation[List[String],List[Int]] = Success(List(1234, 12, 34))
scala> all[({ type l[a] = Validation[List[String], a] })#l, Int]("asfasf", List(oneV, twoV, threeV))
res14: scalaz.Validation[List[String],List[Int]] = Failure(List(For input string: "asfasf", For input string: "as", For input string: "fasf"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment