Created
May 17, 2013 22:52
-
-
Save maxdeliso/5602472 to your computer and use it in GitHub Desktop.
simple blocking future with scala
This file contains hidden or 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
| import scala.annotation.tailrec | |
| import scala.concurrent._ | |
| import scala.concurrent.duration._ | |
| import ExecutionContext.Implicits.global | |
| import java.io.EOFException | |
| import java.lang.NumberFormatException | |
| object Sandbox extends App { | |
| abstract class IOResult | |
| case class IOSucceeded(userInt: BigInt) extends IOResult | |
| case class IOFailed() extends IOResult | |
| override def main(args: Array[String]) = { | |
| print("enter an int, and I'll compute the factorial: ") | |
| val userIntFuture: Future[IOResult] = future { | |
| try { IOSucceeded(readInt()) } | |
| catch { | |
| case eof: EOFException => | |
| println("EOF") | |
| IOFailed() | |
| case nfe: NumberFormatException => | |
| println("NaN") | |
| IOFailed() | |
| } | |
| } | |
| userIntFuture onFailure { | |
| case err => | |
| println("couldn't get int: " + err.getMessage()) | |
| } | |
| val userIO = Await.result(userIntFuture, Duration.Inf) | |
| userIO match { | |
| case success: IOSucceeded => | |
| if (success.userInt >= 0) { | |
| println(success.userInt + "! = " + fact(success.userInt)) | |
| } else { | |
| println("factorial is undefined for " + success.userInt) | |
| } | |
| Unit | |
| case failure: IOFailed => | |
| Unit | |
| } | |
| } | |
| def fact(x: BigInt) = { | |
| @tailrec | |
| def factRec(x: BigInt, acc: BigInt): BigInt = { | |
| if (x > 0) factRec(x - 1, acc * x) | |
| else return acc | |
| } | |
| factRec(x, 1) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment