MyArchiBook

Archive for September 2013

memoize() in Groovy

with 5 comments

Memoization generally means remembering the output for the already passed input.

In Groovy, memoization is performed using memoize().

An example of memoize() called on closures is given below,

Example:

def toSquare={a->
  sleep(2000)
  a*a
}.memoize()

//Case 1:
println toSquare(5)           // O/P:25 --> Got after 2000ms
//Case 2:
println toSquare(5)           // O/P:25 --> Got IMMEDIATELY
//Case 3:
println toSquare(6)           // O/P:36 --> Got after 2000ms

In the above code,There is a closure toSquare.

Here any  parameter that is passed into the closure is squared only after 2000ms and above all, the closure is Memoized.

  • Case 1 : When the closure is called for the first time and parameter 5 is passed, the computation is done completely . In accordance with the computational flow, the result is printed only after 2000ms .
  • Case 2: When the closure is called for the second time and the same parameter 5 is passed, computation is not done and the result is displayed immediately. This is becuase of the memoize(). i.e., By Memoization principle , it stores the calculated value of the input that has been passed already.
  • Case 3: Here , a new input is being passed. Computation is done.Result is displayed after 2000ms. However now that , this result for this particular input will be cached.

memoize()                                     –> stores all the new inputs and the corresponding outputs.

memoizeAtLeast(minimum)  –> stores atleast a minimum number of results.

memoizeAtMost(maximum) –> stores the maximum number of results specified .

 

Have a memoizable day 🙂

Advertisements

Written by thangaveluaishwarya

September 21, 2013 at 11:25 PM

Operator ad-hoc Polymorphism in Groovy

with 2 comments

Operator ad-hoc polymorphism most commonly known as Operator Overloading, expresses about the polymorphic(more than one)  behaviour exhibited by the operator at different contexts.

In Groovy, this behaviour depends on the operands on both sides.

Let’s look at it.

def a="ten"; b=2.5; c=3; d=[]; e=[:]

//Case 1
result=a+b
assert result=='ten2.5'
assert a+b==a.plus(2.5)
println result.getClass()                    //O/P: class java.lang.String

//Case 2
result=b+c
assert result==5.5
println result.getClass()                    //O/P: class java.math.BigDecimal

//Case 3
println c.getClass()                        //O/P: class java.lang.Integer
c+=50000000000000
assert c==50000000000003
println c.getClass()                        //O/P: class java.lang.Long
c+=1000000000000000000000000
println c.getClass()                        //O/P: class java.math.BigInteger

//Case 4
d+=100
assert d==[100]

e+=['A':1,'B':2,'C':3]
assert e==['A':1,'B':2,'C':3]

//Case 5
def f='!'
println f*10                               //O/P: !!!!!!!!!!
assert f*10==f.multiply(10)

In the above code, each variable is of different type and the operator behaves accordingly.

  • Case 1: + Operator appends the BigDecimal value to a String and the result is of String type. 
    In Groovy, a decimal number, by default is of BigDecimal type. Instead of + operator,  . plus() method can also be used.

Like .plus(),  there are various methods corresponding to a particular operator function. You can check it out over here.

  • Case 2: + Operator performs the operation of summing a BigDecimal value and and an Integer. Here the result type is BigDecimal.
  • Case 3: Before going into the third case, let’s get to know of something…

When I assign a number value to a def variable, groovy takes into account, the smallest variable type that accomodates that particular value.

Here in this case of c , the type is Integer. As the size of the variable increases , it would make it the instance of Long or BigInteger which are of greater sizes. Therefore the order is Integer–> Long–> BigInteger.

  • Case 4:+ Operator performs the action of adding elements to the list d and map e.
  • Case 5: If we want to print a String n number of times, it can be done by multiplying the String by an integer as shown in above code case 5.

In all the above cases,we can see that, an operator decides its nature of operation  based upon the behaviour and type of the operands.

== and .equals():

In groovy, == and .equals carry the same meaning.  It checks for value equality.

def a='abcd'
println a=='abcd'                  //O/P: true
println a.equals('abcd')           //O/P: true

But == and .equals are not the same in GString Implementation.

def a='abcd'
println "$a"=='abcd'               //O/P: true
println "$a".equals('abcd')        //O/P: false

GStrings are again behaving in a strange way.

The reason is that, GString’s .equals() method takes in argument that is an instance of GString and not of any other type, be it even a String.

SAFE-NAVIGATIONAL OPERATOR:

Groovy has provided us an extra flexibility with handling the ever torturing NullPointerException.

Let’s see how…

a=null
result=a.plus(8)         // Null Pointer Exception thrown
result=a?.plus(8)        // O/P: null

In the above case , we can see that ,

SAFE NAVIGATIONAL OPERATOR ‘?’ checks null and prevents NullPointer Exception to be thrown.

Safe Navigational Operator shouldn’t be followed by another operator. If done so , it wont work.

RANGES:

Here a sequence of elements are got  when the Lowest value and the Highest Value is specified.. The sequence can be a sequence of number/ character .

Ranges extend java.util.List class.

Range Object is a List Object. i.e., the output is obtained in List form.

Range is defined as below,

def a=10..7
assert a==[10,9,8,7]

It can also be defined by using a spread operator(*).

def b=[*'a'..'h']
assert b==['a','b','c','d','e','f','g','h']

Here spread operator  extracts and spreads individual values in the form of a List object.

SPREAD-DOT OPERATOR(*.):

class GreWordDetails{
    String greWord
    String wordMeaning
    def explanation(){
     "$greWord means $wordMeaning"
    }
}
def wordList=[
      new GreWordDetails(greWord:'abash',wordMeaning:'ashamed'),
      new GreWordDetails(greWord:'enigma',wordMeaning:'mystery')
]
println wordList*.explanation()

O/P:[abash means ashamed, enigma means mystery]

It is said , The spread-dot operator (*.) is used to invoke a method on all members of a Collection object.

In the above code,  this operator invokes the explanation() method on the members of wordList object and spreads the result.

ELVIS Operator(?:):

This operator is a CUT SHORT form of TERNARY OPERATOR

b=(a!=null)?a:false can also be written as b=a?:false

Groovy Operators are not just this.. There are lots of other things like Spacechip Operator, EXOR, AND, OR,Power Operator and etc.,

Have a nice day 🙂