Omgo's Blog

October 18, 2010

scala simple number guess application using case pattern guards

Filed under: scala — aswin @ 11:15 pm

There are millions of examples out there on all this, but here is a little program that shows the case pattern guards and function literals

class NumGuessCase(guess: Int) {

  def guessNum(read: () => Int, disp: String => Unit): Unit = _guessNum(read, disp)

  private def _guessNum(read: () => Int, disp: String => Unit, times: Int = 0): Unit = {
    disp("Please enter guess :> ")    
    read() match {
      case `guess` => disp("You guessed right in " + (times+1)); 
      case a if a > guess => disp ("You guessed too high");
                _guessNum(read, disp, times+1)
      case a if a < guess => disp ("You guessed too low");
                _guessNum(read, disp, times+1)
    }
  }

}

The guessNum method takes two arguments, read, and disp. Parameter “read” is a function which when invoked should return the user’s guess. “disp” (display) represents a function which is responsible for the output of the messages by the guessNum function. So the client of the guessNum can pass in as arguments a function that accepts user input and another one that displays the messages back to user and in our case we just use system console for this interaction (see the NumGuesCase companion object shown below).

The part I was testing out was the case pattern guards, the second case statement would match only if the pattern guard (“a > guess”) returns true. We could have used a default catch all pattern (“_”) as the last case statement. The first statement uses a variable pattern and is why you have to use the ` (backquote) symbol.

object NumGuesCase extends Application {
  new NumGuessCase(new java.util.Random().nextInt(100)).guessNum(readInt,println)
}

This is how you would use the guessNum method, just pass in a readInt and println method. Scala compiler would capture these methods as Fuction objects and pass it to our guessNum method and since they both Type check with the Function signature it works.

If anyone is trying this out , please be aware of the missing main method bug (pre 2.8.0) as detailed out here

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Create a free website or blog at WordPress.com.

%d bloggers like this: