Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Created May 17, 2013 22:52
Show Gist options
  • Select an option

  • Save maxdeliso/5602472 to your computer and use it in GitHub Desktop.

Select an option

Save maxdeliso/5602472 to your computer and use it in GitHub Desktop.
simple blocking future with scala
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