Last active
December 17, 2015 11:50
-
-
Save maxdeliso/5605738 to your computer and use it in GitHub Desktop.
Better, cleaner, briefer, more idiomatic use of Scala's Console
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 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