Created
August 12, 2011 17:28
-
-
Save philwills/1142511 to your computer and use it in GitHub Desktop.
Stream example gist
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 FailingNumberFinder { | |
def findMagicNumber(numbers: Seq[Int]) : Option[Int] = { | |
for(number <- numbers) { | |
try { | |
return Some(SlowErrorProne.search(number)) | |
} catch { | |
case _ => | |
} | |
} | |
return None | |
} | |
} |
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 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 | |
} | |
} |
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 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 | |
} | |
} |
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 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 | |
} | |
} |
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 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