Wednesday, September 19, 2012

Scala Functions Apply

This is a short post about sweet spots of scala functions such as apply, update and case classes using these constructs.

Coming from a Ruby world, developers usually snub at Java claiming Javascript and Java, substring of JS are a mere naming coincidence, without any functional relations. Hmm, perhaps recent hot cake Functional programming which has been tombed in Egypt several thousand years back is a mirage in Java community, where java is targeted for non functional, non mathematical people, who well mutate everything in their life apart from Java. Apparently some serious thought breakers ice sandwiched Java and started exploding JVM that catered to beautiful languages like Scala and Clojure.

Scala bieng a functional language believes in functions being first class citizens with a slight mix of object oriented programming orthogonal to it. This helps in writing clean, concise, expressive code.

Here are some experiments by firing scala REPL,

To define an anonymous function,
val cube = (x:Int) => x * x * x
#cube: (Int) => Int = <function1>
cube(5)
#125
Its clear that it takes an argument Int and returns an Int. Further we can explicitly specify return type say Double,
val cube: (Int) => Double = (x) => x * x * x
#cube: (Int) => Double = <function1>
When I started exploring function1, I landed on to interesting landscape, behind the scenes scala does million number of things by providing this sugar coated pill.

function1 is actually an interface with apply method and anonymous class out of it is created copying the method definition inside apply method. In fact the above cube function could be written in this way too,
val cube: Function1[Int, Double] = (x) => x * x * x
#cube: (Int) => Double = <function1>

cube.apply(5)
#res2: Double = 125.0

cube(5)
#res3: Double = 125.0
look how scala beautifully desugars cube(5) to cube.apply(5).

The Function1 would probably be a interface like this
public interface Function1<A, B> {
    B apply(A a)
}
and creating anonymous class at runtime, copying method definition inside apply method like below(note - below I refer Scala types and not Java)
cube = new Function1<Int, Double>() { Double apply(Int a) { a * a * a }}
cube.apply(5) #actual way
cube(5) #sugar coated pill in Scala
now if I have a polynomial equation, say x^2 + y^2 the thing would be even more beautiful,
val square: Function2[Int, Int, Double] = (x, y) => x * x + y * y
#square: (Int, Int) => Double = <function2>

square(4,5) #square.apply(4,5)
#res0: Double = 41.0
The deduction here is, if n is the size of arguments with last being return type, then the interface name would be function{n-1}.

In the last example we had two unknown variables x, y and return type - hence Function2.

In fact any class with apply method works same way,
class ApplyTest {
    def apply(in: Int) = in + in.toString
}

val applyTest = new ApplyTest()
#applyTest: ApplyTest = ApplyTest@5292e6

applyTest(5) #applyTest.apply(5)
#res0: String = 55

Usage of apply method in real time applications

apply function syntactic sugar could be used to fetch domain object  or model object from a singleton, example
object Employee {
    def apply(id: Int) = "retrieving from database employee object id " + id
}

Employee(5) #res1: java.lang.String = retrieving from database employee object id  5

There is another sugar coated pill in scala - update function which I will cover it in next post.

Sunday, June 17, 2012

to_proc working magic

I had an interesting puzzle in ruby to capitalize words with in a string.
text = "this is an interesting blog post about to_proc"

text.split.map(&:capitalize).join ' '

# "This Is An Interesting Blog Post About To_proc" 

Just was nailing down the answer I got, with the internals wired.
Normally single argument block comes after a map like this,
{ |arg| arg.capitalize! }

But how does ruby allows us to use syntactic sugar coated pill like passing a symbol to a map?
Explanation can be found here, symbol to_proc.
Need to smell some samples & create your own version of it? Here below...
class MyString < String

  def double
    self * 2
  end

  def triple
    self * 3
  end

  def map_char(&p)
    result = []
    self.each_char do |c| 
      result << p.call(c)
    end
    result.join
  end

end


name = MyString.new("hariharan")

#usual way
p name.map_char { |m| m * 2} # "hhaarriihhaarraann" 

#syntactic sugar coated pill
p name.map_char(&:triple) # hhhaaarrriiihhhaaarrraaannn

On whole, the mist here is class 'Symbol' has a to_proc method, that accepts  object  as an argument and passes the message of 'symbol' to that object.

Stay tuned for my next blog about scala magic sugar coated stuff...

Saturday, February 4, 2012

Java 8 Lambda a terrible troll and Java is lame duck

            Nothing more to scare about the title, and more, this is not a post to slam or defamatory content against java. The Recent announcement about java 8 to support lambda and introduce functional programming abilities to java made me to wonder, really do we need this? Once my friend Mr.Balan said its Steve Jobs ,not apple and apple would had not been great without steve jobs. Its all about people who make things great rather than believing group or companies.

            Thanks to Mr. Cedric Beust whom  I respect a lot, his outstanding creation TestNG. The title of this post is the tweet he mentioned on me noting 'Terrible troll' when I asked 'Why google endorses java and why not something better than it'. Google employee tweeted saying that 'Google would had invented java if not exist'. More, google employees does not show overwhelming response to new JVM/CLR languages like scala and clojure. However Cedric can write some disappointing post like coding in high level type system languages would eclipse if not using eclipse from  scala back to java. This post made my adrenaline going. In fact prestigious, proud ruby developers use vim, yes honest authentic passionate ruby developers use vim, while some use textmate for ruby coding.

            Then I looked back at my poor java announcement that any chance for atleast java 8 to swing the theories of Functional programming. But in vain, where my respected oracle developers traveled with camels to thar desert, sat under khejri tree, intensively thought about building expensive lambda islands in par to what Dubai tries to. Unfortunately they failed like creating Indian Mumbai building constructions with poor quality material. In 2002 C# finished chapter, Scala moreover finished in providing lambda in 2005. Then, what is the point in creating a huge buzz about lambda in java 8 by the year 2012, then saying 'Java will adopt C# syntax'? This should have been wisely copied or taken 8 years back.

            Java already screwed with some concepts like anonymous inner classes. Though I am not object oriented or based specialist, but really I could not connect with reality about class nesting inside a class. Can a person nest a  person inside? If so what is the use of that.

            Actually speaking, this is what happens with sorting a collection, where comparable interface is implemented and collection.sort in turn calls the comparaTo method for status, to swap the element positions. But where is the thrill?

            Java 8 lambda is a lame duck. Because there are no first class functions. Functions are not senior citizens. Otherwords, its more or less same way of achieving to sort a collection by implementing comparable interface. Whereas in scala, functions are senior citizens. Let me get straight to examples.

Open scala prompt, to find a minimum element in an list,

val values = List(1, 2, 3, 4, 5)
println(values.foldLeft(0) { (acc_res: Int, index: Int) => if(index < acc_res) index else acc_res }) 
//prints 0 //To find maximum, (just change the comparison symbol :)) def maxi(acc_res: Int, index: Int) = { if(index > acc_res) index else acc_res } println(values.foldLeft(0) { maxi }) //prints 5


What the same to do in Java, to find the minimum element, comparable interface must be implemented or custom interface is created in favorite naming in favorite eclipse, that hangs windows xp for 5 mins, a method declared in interface, and then defined to return status in implementation class. Finally call made to implementation class that implements of type 'comparable' sort of interface(or custom interface)

Now coming to Java 8 Lambda, serious comedy fuels, just look at the sample lambda program

public class SimpleLambda {
  interface HelloWorld {
    void greet();
  }

  {
    HelloWorld greeting = () -> System.out.println("Hello World!");
    greeting.greet();
  }

  public static void main(String... args) {
    new SimpleLambda();
  }


}


Type of anonymous functions or lambda? Its the same as interface.
Hence interface should be defined prior to assigning a anonymous function which is not the intent of lambda in other languages.

To add, a question already in heavy discussion on quora for oracle to declare explicit support to scala instead of spreading fad.

Since Java ones are tamarind to declarative programming, scala itself more sufficient.

Microsoft .NET can better declare explicit support for clojure, as I believe C++ and C# programmers be intuitive and pick up clojure on CLR.

James gosling intent of java is just to please the average coders, I am not one and you too.,,

Enjoy functional programming, DSL and kudos to Scala and Clojure.