Skip to content

Instantly share code, notes, and snippets.

@hamidr

hamidr/mygist.scala

Last active Nov 10, 2017
Embed
What would you like to do?
object MyTest {
def main(args: Array[String]): Unit = {
println(sequence1(Seq(Some(1), None, Some(2), None)))
println(sequence2(Seq(Some(1), Some(3), Some(2), Some(5))))
}
def sequence1[T](items: Seq[Option[T]]): Option[Seq[T]] = {
items.foldLeft(Option(Seq[T]())) { (res, e) =>
e match {
case Some(value) => Option(res.getOrElse(Seq[T]()) :+ value)
case None => None
}
}
}
def sequence2[T](items: Seq[Option[T]]): Option[Seq[T]] = {
var ns = Seq[T]()
var state = false
items.takeWhile {
case None => {
state = true
false
}
case Some(n) => {
ns = ns :+ n
true
}
}
if (!state) Some(ns)
else None
}
def sequence3[T](items: Seq[Option[T]]): Option[Seq[T]] = {
try {
items.foldLeft(Option(Seq[T]())) { (res, e) =>
e match {
case Some(value) => Option(res.getOrElse(Seq[T]()) :+ value)
case None => throw new Exception("reached where it shouldn't")
}
}
} catch {
case _: Throwable => None
}
}
def sequence4[T](items: Seq[Option[T]]): Option[Seq[T]] = {
try {
val ns = items.map {
case Some(n) => n
case _ => throw new Exception("stop me :))")
}
Some(ns)
} catch {
case _: Throwable => None
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.