Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Functional object


Published on

Published in: Technology
  • Be the first to comment

Functional object

  1. 1.    Introducing Functional  Objects  Ruchi Jindal                                      Software Consultant    Knoldus
  2. 2. What is Functional Programming It must be true: x == y <==> f( x ) == f( y ) In a functional language, a function is a value of the same status as, say,an integer or a string.Eg :1+2 OR Matrix1+ Matrix2 You can pass functions as arguments to other functions & return them asresults from functions,or store them in variables. Define a function inside another function. Define functions without giving them a name.
  3. 3. What is Functional Object Functional objects is a objects that do not have any mutable state. Immutable objects not have complex state spaces that changeover time. We can pass immutable objects whereas we may need to makedefensive copies of mutable objects before passing them to othercode. No thread can change the state of an immutable object.
  4. 4. Function Currying in ScalaCurrying is the technique of transforming a function that takes multiplearguments into a function that takes a single argument.Eg:def add(x:Int, y:Int) = x + yAnd after currying:def add(x:Int) = (y:Int) => x + yAdd(1)(2) // 3The second example redefines the add method so that it takes only a singleInt as a parameter and returns a functional (closure) as a result.
  5. 5. Partials v/s Currying Partial Function Curryingdef add(x:Int, y:Int, z:Int) = x + y + z def add(x:Int, y:Int, z:Int) = x + y + zval addFive = add(5, _:Int, _:Int) val addFive = (a:Int, b:Int) => add(5, a, b)Scala> addFive(3, 1) //9 Scala> addFive(3, 1) // 9
  6. 6. Constructing a Rational Objectclass Rational(n: Int, d: Int)here n & d are class parameters.The Scala compiler will gather up these two class parameters and create aprimary constructor that takes the same two parameters.scala> new Rational(1, 2)res0: Rational = Rational@90110a
  7. 7. Reimplementing the toString methodWe can override the default implementation by adding a method toString toclass Rational, like this:class Rational(n: Int, d: Int) {override def toString = n +"/"+ d}scala> val x = new Rational(1, 3)x: Rational = 1/3
  8. 8. Checking preconditionsclass Rational(n: Int, d: Int) {require(d != 0)override def toString = n +"/"+ d}The require method takes one boolean parameter.require will prevent the object from being constructed by throwing anIllegalArgumentException.
  9. 9. Adding Fields//wont compileclass Rational(n: Int, d: Int) {require(d != 0)override def toString = n +"/"+ ddef add(that: Rational): Rational =new Rational(n * that.d + that.n * d, d * that.d)}Here add method is the fieldthat.n or that.d, because that does not refer to the Rationalobject on which add was invoked
  10. 10. //here is the correct exampleclass Rational(n: Int, d: Int) { require(d != 0) val numer: Int = n val denom: Int = d override def toString = numer + "/" + denom def add(that: Rational): Rational = new Rational( numer * that.denom + that.numer * denom, denom * that.denom)}
  11. 11. scala> val rational = new Rational(1, 2)rational: Rational = ½scala> rational.numerres1: Int = 1scala> rational.denomres2: Int = 2scala> val oneHalf = new Rational(1, 2)oneHalf: Rational = ½scala> val twoThirds = new Rational(2, 3)twoThirds: Rational = 2/3scala> oneHalf add twoThirds // oneHalf.add(twoThirds)res3: Rational = 7/6
  12. 12. Self referencesthis refers to the self reference .def add(that: Rational): Rational = new Rational( this.numer * that.denom + that.numer * this.denom, this.denom * that.denom)scala> val oneHalf = new Rational(1, 2)oneHalf: Rational = ½scala> val twoThirds = new Rational(2, 3)twoThirds: Rational = 2/3scala> oneHalf add twoThirdsres3: Rational = 7/6
  13. 13. Auxiliary constructorsIn Scala, constructors other than the primary constructor are calledauxiliary constructors.Auxiliary constructors in Scala start with def this(...)class Rational(n: Int, d: Int) {def this(n: Int) = this(n, 1) // auxiliary constructor}scala> val rational = new Rational(3)rational: Rational = 3/1
  14. 14. Private fields and methodsclass Rational(n: Int, d: Int) {private val g = gcd(n.abs, d.abs)val numer = n / gval denom = d / gdef this(n: Int) = this(n, 1)override def toString = numer +"/"+ denomprivate def gcd(a: Int, b: Int): Int =if (b == 0) a else gcd(b, a % b)}scala> new Rational(50,10)res1: Rational = 5/1
  15. 15. Defining operatorsWe can write operation(+,*,-,/.....) on functional object as same as integerobject likeeg def + (that: Rational): Rational =new Rational(numer * that.denom + that.numer * denom,denom * that.denom)scala> onehalf + twothird //onehalf.+(twothird)res1: Rational = 7/6It is same as 1+2 or 1*2
  16. 16. Scala’s also follows the rules for operator precedence.Eg:x + x * y will execute as x + (x * y), not (x + x) * y:scala>oneHalf + oneHalf * twoThirdsres1: Rational = 5/6The above expression will evaluated asoneHalf.+(oneHalf.*(twoThirds))
  17. 17. Method overloadingscala>oneThird + 2 // oneThird.+(2)res1: Rational = 7/3def + (that: Rational): Rational =new Rational(numer * that.denom + that.numer * denom,denom * that.denom)def + (i: Int): Rational =new Rational(numer + i * denom, denom)
  18. 18. Implicit conversionsOneHalf * 2 // compile because it convert into OneHalf.*(2)2 * OneHalf // wont compile because it convert into 2.*(OneHalf)To resolve this implicit conversion is used.scala> implicit def intToRational(x: Int) = new Rational(x)This defines a conversion method from Int to Rational.scala> val r = new Rational(2,3)r: Rational = 2/3scala> 2 * rres1: Rational = 4/3
  19. 19. Object Equality The == equality is reserved in Scala for the“natural” equality of each type. For value types, == is value comparison. We can redefine the behavior of == for new types by overriding the equalsmethod,which is always inherited from class Any. It is not possible to override == directly, as it is defined as a final method inclass Any. If two objects are equal according to the equals method, then calling thehashCode method on each of the two objects must produce the same integerresult.Eg:var r1=new Rational(1,2)var r2=new Rational(-1,2)scala> r1 equals r2 //false
  20. 20. Example of equality on Rational classoverride def equals(other: Any): Boolean = other match { case that: Rational => (that canEqual this) && numer == that.numer && denom == that.denom case _ => false } def canEqual(other: Any): Boolean = other.isInstanceOf[Rational] override def hashCode: Int = 41 * ( 41 + numer) + denom