I went hiking on the Rocky mountains, Colarado with Venkat Subramaniam, author of Programming Scala. More than the hike, the numerous technical discussions we had during the hike, were more enjoyable. After we came back we decided to give the Guessing game a complete immutability shot with recursion and lazy collections. Given below is the immutable Guessing Game using recursion. In the process, thanks to Venkat, ironed out issues on Scala language that were bothering me for quite sometime.
Here’s the class Game that has a play method which is recursively called till the game is over. The input and output providers are injected into the method using Closures.
object Game { val target = (Math.random * 100).toInt def play(attempts : Int = 1)(printer: String => Unit)(reader: Unit => Int) { printer("Enter your guess:") val guess = reader() val compared = guess.compare(target) val (message, playAgain) = compared match { case -1 => ("Aim higher", true) case 0 => (s"You got it in $attempts attempts", false) case 1 => ("Aim lower", true) } printer(s"$messagen") if(playAgain) play(attempts + 1)(printer)(reader) } } println("I've picked a number, can you guess it?") Game.play() { msg => print(msg) } { Unit => Console.readInt }
Apparently Venkat is also writing an article on this topic. So I have published this code with due permission.