Skip to content

Instantly share code, notes, and snippets.

@philwills
Created August 12, 2011 17:28
Show Gist options
  • Save philwills/1142511 to your computer and use it in GitHub Desktop.
Save philwills/1142511 to your computer and use it in GitHub Desktop.
Stream example gist
object FailingNumberFinder {
def findMagicNumber(numbers: Seq[Int]) : Option[Int] = {
for(number <- numbers) {
try {
return Some(SlowErrorProne.search(number))
} catch {
case _ =>
}
}
return None
}
}
object FasterMagicNumberFinder {
def findMagicNumber(numbers: Seq[Int]) = {
def attemptSearch(number: Int) = {
try Some(SlowErrorProne.search(number))
catch { case _ => None }
}
val magicNumbers = Stream(numbers: _*) flatMap (
attemptSearch(_)
)
magicNumbers.headOption
}
}
object SimpleMagicNumberFinder {
def findMagicNumber(numbers: Seq[Int]) = {
def attemptSearch(number: Int) = {
try Some(SlowErrorProne.search(number))
catch { case _ => None }
}
val magicNumbers = numbers flatMap (
attemptSearch(_)
)
magicNumbers.headOption
}
}
object SlowErrorProne {
val MAGIC_NUMBERS = List(3, 42, 666)
def search(number: Int) = {
Thread.sleep(500)
if (MAGIC_NUMBERS contains number) number
else throw new Exception
}
}
object UglyNumberFinder {
def findMagicNumber(numbers: Seq[Int]) : Option[Int] = {
def attemptSearch(number: Int) = {
try Some(SlowErrorProne.search(number))
catch { case _ => None }
}
for(number <- numbers) {
val result = attemptSearch(number)
result match {
case Some(magic) => return Some(magic)
case _ =>
}
}
return None
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment