Skip to content

Instantly share code, notes, and snippets.

@philwills
Created February 9, 2015 21:22
Show Gist options
  • Save philwills/687dc61388385568c86a to your computer and use it in GitHub Desktop.
Save philwills/687dc61388385568c86a to your computer and use it in GitHub Desktop.
Sequencing Either
package ophan
object Or {
type Or[T] = Either[String, T]
def traverse[A,B](seq: Seq[Or[A]])(f: A => B): Or[Seq[B]] = {
seq.foldLeft[Or[Seq[B]]](Right(Nil)) { (acc, or) =>
or match {
case Left(s) => Left[String, Seq[B]](s)
case Right(a) => acc.right.map(_ :+ f(a))
}
}
}
def sequence[T](seq: Seq[Or[T]]): Or[Seq[T]] = traverse(seq)(identity)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment