Last active
November 10, 2017 07:44
-
-
Save hamidr/95826b4e2e605eea517a38670148451b 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
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