Skip to content

Instantly share code, notes, and snippets.

@maxdeliso
Last active December 17, 2015 11:50
Show Gist options
  • Save maxdeliso/5605738 to your computer and use it in GitHub Desktop.
Save maxdeliso/5605738 to your computer and use it in GitHub Desktop.
Better, cleaner, briefer, more idiomatic use of Scala's Console
import scala.annotation.tailrec
import java.io.EOFException
import java.lang.NumberFormatException
object Sandbox extends App {
override def main(args: Array[String]) = {
print("Enter an int, and I'll compute the factorial: ")
val done = for {
userInt <- safeIntRead()
valid <- Some(userInt) if userInt > 0
done <- Some(fact(valid))
} yield done
println( done getOrElse "could not compute" )
}
def safeIntRead() = {
try{ Option(readInt) }
catch {
case _ => None
}
}
def fact(x: BigInt) = {
require(x >= 0)
@tailrec
def factRec(x: BigInt, acc: BigInt): BigInt = {
if (x > 0) factRec(x - 1, acc * x)
else acc
}
factRec(x, 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment