Prabhu Sunderaraman

Fullstack Engineer, Programmer, Writer, Trainer

prabhu.bits@gmail.com,     GitHub     Youtube     LinkedIn
  • Home
  • Profile
  • Books
  • Reading List
Browsing: / Home
Shortlink

Operator Overloading in Scala

By Prabhu Sunderaraman on June 5, 2013 in Scala

Operators like +, – , * and so on are actually not operators in traditional sense in Scala language. They all are methods. :). Scala language provides a relaxed syntax when it comes to method invocations. The dot (.) and braces between the objects and method names are optional. When you say object1 + object2 it actually is translated into object1.+(object2).

Therefore operator overloading in Scala means implementing a method with the operator as the name of the method. Let’s learn this with an example. We’ll create a class called Shape with height and width variables. We’ll implement the + and * methods as shown below.

class Shape(private val theHeight:Int,private val theWidth:Int){
  val height = theHeight;
  val width = theWidth;
  def +(another:Shape):Shape = {
     new Shape(this.height+another.height,this.width+another.width)
  }
  def *(another:Shape):Shape = {
	new Shape(this.height*another.height,this.width*another.width)	  
  }
}

You can invoke the + and * methods on Shape objects as shown below.

var shape1 = new Shape(10,20)
var shape2 = new Shape(30,20)
var shape3 = shape1 + shape2
println(shape3.height + ", " + shape3.width)//Prints 40,40

var shape4 = shape1 * shape2
println(shape4.height + ", " + shape4.width)//Prints 300,400

You can invoke + and * methods together. You don’t have operator precedence in Scala however. Instead Scala has method priorities. If you invoke multiple methods in a single statement the asterik, slash characters are given high priority followed by the plus, minus and so on. The methods with letters have the least priority. So if you have a method call like this obj1 + obj2 * obj3 foo(obj4). The asterik method is invoked first, followed by plus and finally the foo method is called.

 var s1 = new Shape(10,20)
 var s2 = new Shape(30,40)
 var s3 = new Shape(50,60)
 var s4 = s1 + s2 * s3 
 println(s4.height + ", " + s4.width) //Prints 1510,2420

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Partially applied functions in Scala

By Prabhu Sunderaraman on May 23, 2013 in Scala

Scala provides a concept called partially applied functions that spares you from writing several lines of code.

Say, you have a function f that accepts 2 arguments. While invoking f you may have to pass both the arguments. In Scala you have an option to invoke f by passing partial list of arguments. You can create a partially applied function of f by passing the first argument alone. Later you can invoke the partially applied function by passing the second argument. Let’s take a close look at it with an example

We have a function that calculates arithmetic progression of n numbers. The function takes in the first number, the common difference and the number of values you want the series to be computed. Here’s the code to do that in Scala

def arithmeticProgression(first:Int,difference:Int,numbers:Int):List[Int]=  {
 var result = List[Int]()
 0 to numbers foreach {x=>result = result :+ (first + (x * difference))}
 result
}

The arithmeticProgression method accepts 3 arguments and returns a series list. You can invoke it like this.

println(arithmeticProgression(1,1,10))

The output of the above code will be List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11). Say you want the arithmetic progression of 10 numbers starting from 1 and with varied values for the difference argument. This is how you will do it traditionally

 println(arithmeticProgression(1,1,10))
 println(arithmeticProgression(1,2,10))
 println(arithmeticProgression(1,3,10))
 println(arithmeticProgression(1,4,10))
 println(arithmeticProgression(1,5,10))

You can notice that the second parameter is the only varying argument here. The first parameter has a constant value 1 and the third parameter also has 10 as its value. You can rewrite it as shown here.

 1 to 5 foreach {i=>println(arithmeticProgression(1,i,10))}

This code still makes too much noise. Let’s rewrite it using partially applied function here.

def ap10 = arithmeticProgression(1,_:Int,10:Int)
1 to 5 foreach {i=>println(ap10(i))}

We’ve created a partially applied function called ap10 by passing 1 and 10 for the first and third arguments and an underscore for the second argument. We can now invoke this function just by passing any integer value to the second parameter alone by writing ap10(1) or ap10(2) and so on.

If you want to change the first and third parameters and keep the difference as constant you can define a partial function as like this.

def ap = arithmeticProgression(_:Int,2:Int,_:Int)
println(ap(1,20))

Partially applied functions in scala serve as useful feature for implementing the method overloading concept in OO languages.

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Pattern matching Guessing game in Scala

By Prabhu Sunderaraman on May 18, 2013 in Scala

Continuing with the posts on Scala where we implemented Guessing game in imperative style and a in a couple of ways using the functional style, let’s implement it using pattern matching facility.

Pattern matching provided in Scala is one of the most widely used features. It’s a glorified form of switch-case statements, though comparing it with a switch-case construct would mean belittling it. Given below is the guessing game implemented using pattern matching feature in Scala.

object GuessingGamePattern {
  val target:Int = (Math.random*100).asInstanceOf[Int]
  
  def play(guess:Int):Boolean = {
    guess match {
      case num:Int if (num > target) => println("Aim Lower");false
      case num:Int if (num < target) => println("Aim Higher");false
      case num:Int if (num == target)=> println("You've got it!!!");true
    }
  }
  
  def main(args:Array[String]):Unit = {
    println("Enter a number between 1 and 100")
    var gameOver = false
    var guess:Int = -1
    var attempts:Int = 0
    while(!gameOver){
		  guess = readLine().toInt
		  gameOver = play(guess)
		  attempts += 1
	  }
	  println("Attempts: " + attempts)  
  }
}

If you take a close look at the play method, you’d notice we’ve used pattern matching. You pass the guess value to the play method and try to match it with the condition and return a boolean value.

Now that, we’ve been playing with guessing game in different ways, we’ll take up another example and implement it using Scala

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Functional style Guessing game in Scala – II

By Prabhu Sunderaraman on May 8, 2013 in Scala

In the previous post, we created the GuessingGame as a functional object that was immutable. It was a little heavy as every operation resulted in a new object. Let’s refactor it a but and see where we land.

All that’s involved is passing in data that has the message, attempts and gameOver information. Let’s create a Tuple to hold this information. We’ll rewrite the play method to return a Tuple that holds this information. The play method will accept the guess number, target and attempts as input, compute the logic and return the tuple as output.

object GuessingGame {

  def play(guess:Int,params:(Int,Int)):(Int,String,Boolean) = {
    val message:String =  if(guess>params._1) "Aim Lower" else if(guess < params._1) "Aim Higher" else "You've got it!!!"
    val gameOver:Boolean = if(guess == params._1) true else false
    (params._2+1,message,gameOver)
  }

def main(args: Array[String]): Unit = {
    println("Enter a number between 1 and 100")
    var guess:Int = -1
    val target:Int = (Math.random*100).asInstanceOf[Int]
    var game = (0,"",false)
    while(!game._3){
	guess = readLine().toInt
	game = play(guess,(target,game._1))
	println(game._2)
    }
    println("Attempts: " + game._1)
  }
}

In the next post, let’s refactor this code further to make it further simple

Share this on: Mixx Delicious Digg Facebook Twitter
Shortlink

Functional style guessing game in Scala

By Prabhu Sunderaraman on May 6, 2013 in Scala

In the earlier post on Scala, we created the Guessing Game class using imperative style. Now you’ve the GuessingGame class implemented using functional style. This is the first attempt in doing that.

Couple of points to keep in mind here is in the functional style the classes are designed to be immutable and the variables are designed to be final using the val keyword. Here’s the code snippet that has the GuessingGame class configured as a functional class.


class GuessingGame(theTarget:Int,theAttempts:Int,theMessage:String,theGameOver:Boolean) {
	val target:Int = theTarget;
	val attempts:Int = theAttempts;
	val message:String = theMessage;
	val gameOver:Boolean = theGameOver;
	def play(guess:Int):GuessingGame = {
	  new GuessingGame(
	      target,
	      attempts+1,
	      if(guess>target) "Aim Lower" else if(guess < target) "Aim Higher" else "You've got it!!!",
	      if(guess == target) true else false
	  )
	}
}
object GuessingGameUser {
	def main(args:Array[String]){
	  var game:GuessingGame = new GuessingGame((Math.random*100).asInstanceOf[Int],0,"",false)
	  println("Enter a number between 1 and 100")
	  var guess:Int = -1
	  while(!game.gameOver){
		  guess = readLine().toInt
		  game = game.play(guess)
		  println(game.message)
	  }
	  println("Attempts: " + game.attempts)
	}
}

Though it’s functional there’s a bit of weight added to the code. In the next post let’s see how we can refactor it and make it lightweight.

Share this on: Mixx Delicious Digg Facebook Twitter
« Previous 1 … 37 38 39 … 64 Next »

Youtube Channel




Categories

  • JavaScript (48)
    • RequireJS (5)
  • Go (44)
  • Golang (44)
  • Ext JS (23)
  • Spring (22)
  • Mobile (21)
  • Scala (20)
    • Play (3)
  • Uncategorized (19)
  • Video Sessions (18)
  • GoG (17)
  • Sencha Touch (16)
  • jQuery (14)
  • Languages (13)
  • Java 8 (12)
  • React JS (11)
  • Kotlin (11)
  • HealthyCodeMagazine (9)
  • Video (9)
  • Objective-C (8)
  • NoSQL (8)
  • Android (7)
  • MongoDB (7)
  • GWT (6)
  • Tools (6)
  • HTML 5 (5)
  • Cloud (5)
  • General (5)
  • Micro services (5)
  • Java (5)
  • Books (4)
  • AWS (4)
  • Software Architecture (4)
  • .NET (3)
  • Elixir (3)
  • Docker (3)
  • Reactive (3)
  • NodeJS (2)
  • RoR (2)
  • Backbone (1)
  • AngularJS (1)

Archives

  • 2020 (49)
  • 2019 (7)
  • 2018 (34)
  • 2017 (15)
  • 2016 (7)
  • 2015 (18)
  • 2014 (31)
  • 2013 (55)
  • 2012 (100)

Search

Subscribe




Copyright © 2025 Prabhu Sunderaraman.

Powered by WordPress and News.