Tuesday, December 24, 2013

Functions as Objects

How are functions treated in Scala?
Are functions objects in Scala?

Functions values are treated as objects in Scala.
Any function definition of type A => B is equivalent to type Function1[A,B] and this can be expanded with below definition

trait Function1[A,B]{
   def apply(x: A): B
}

So such traits actually supported by Scala. Function1, Function2,... Function21 in scala package. With such support Scala does support Function definition with 22 parameters.

Anonymous Functions

Expanding the above conversation to see how Anonymous Functions are supported.
For example:

(x: Int) => x * x

when expanded per the above definition below is the structure:

new Function1[Int,Int]{
  def apply(x: Int): Int = x * x  
}

The above definition suggest similar to anonymous class structure provided by Java.

Function Calls

Above discussion provides an understanding of function definition treatment in Scala, but how about function calls. Funtion calls maps to apply method as describe in the structure above.

Lets expand this discussion in terms of below definition which declares an anonymous function and further a call is made to the function:

val f = (x:Int) => x*x
f(2)

val f = new Function1[Int,Int]{
  def apply(x: Int): Int = x * x  
}
f.apply(2)


def f(x: Int): Int = f(x)
out of this (x: Int) => f(x) is treated as anonymous function and expanded by Scala in a similar way discussed above. This translation of a name f is termed as 'eta - expansion' in lamda calculas.

Wednesday, December 18, 2013

Polymorphism in Scala

Is Scala polymorphic? Incase yes, what are the different ways with which this is supported?

Scala being a hybrid of object & functional programming paradigmn, supports polymorphism. Scala support two polymorphism forms:

Subtyping: 

Instances of subclass can be passed to functions instead of declared base class.

Generics:

Functions and classed driven via type parameterization.
  1. Function can be applied to arguments of many types (via generics support at method level)
  2. The type can have instance of many types (via generics support at class level)
Field definition in Scala are special cases of method overriding. They can implement abstract method overriding and traits.

Below are a few highlights in the example:
  1. Cons(val head: Int, val tail: IntList) declares both parameter and field of the class. By declaring this it automatically overrides the abstract definition for head and tail methods.
  2. Generic Type parameter using [T] similar to type definition in Java via <T>
  3. Type parameters are not just limited to classes, but they can be declared at method level as well.
Since Nothing is a subtype of any other type and this is true for T as well. Therefore below syntax is valid and there by this method can be overrided with below definition
def head: Nothing = throw new NoSuchElementException("head.nil")
def tail: Nothing = throw new NoSuchElementException("tail.nil")

Saturday, December 14, 2013

Good Story

Thanks Stephen

Mutter Paneer


This one is not about Scala ;)

Being a weekend thought of preparing something special today. And the very moment heard Mutter wala selling mutter (peas) out side. This reminded me of Mutter-Paneer which SVJ brought yesterday for his evening meal.

Bingo, Why not try Mutter Paneer today!! 

Googled the recipe and stumble upon Nisha Madhulika's site, this details the recipe and that too a Jain version. Followed the steps suggested by her and here it is (on the left) !! 

Comments:
Mumma: She liked it but found it a bit sweet. I haven't added any sugar, looks like peas were sweet.
Shrut: She too find it a less spicy one and bit sweet. But overall it was a nice preparation.
Aryaa: She's the critic, never eat what I prepare.. :(
Me: I liked it, it was delicious. Honest comments.
After eating went to for a nap for 2 hours. Made my day !!

From this experiment, I now believe that such meals can be prepared at home and with better taste then how it is served at restaurants. I am fond of cooking & this experiment has encouraged me.
Now my next goal is to get some Mexican dish prepared at home. I have tasted one such dish at Chipotle and since then I loved it.

Tuesday, December 3, 2013

Operator Overloading in Scala

Does Scala support Operator Overloading?

If I go by below definition then I would say yes it does.
In object-oriented programming, operator overloading—less commonly known as operator ad hoc polymorphism—is a specific case of polymorphism, where different operators have different implementations depending on their arguments. Operator overloading is generally defined by the language, the programmer, or both.
Below is an example which elaborates on how is this supported. I am extending  binary <, unary pre negation (-) and unary post ++ operator for a custom datatype Rational.

Wednesday, November 20, 2013

Data structures in Scala

How do I define my own data structures in Scala? Or does Scala does support some encapsulation mechanism?

Class similar to Java are supported in Scala. I wonder if Scala support Class then is Scala object oriented? Need to give a serious thought on this question. Any ways let me not create confusion here and first discuss the class constructs supported in Scala. Below example discuss encapsulation of rational number type and supporting various arithmetic associated.


Tuesday, November 19, 2013

Higher Order Functions

What does it mean by functions as first class values? Or, what are higher order functions?

There are languages which supports passing functions as arguments to other functions, returning them as the values from other functions, and assigning them to variables or storing them in data structures. Scala is one such language which does support higher order functions, scala worksheets below explains some of these with examples:



Sunday, November 10, 2013

First Class Citizen

What are First Class Citizens?

'First Class Citizen', I have gone through this sentence many times but never bothered on what does this really mean.
But yersterday while going through basics of 'Functional Programming', another programming paradigm, I stumbled upon 'Functions as First Class Citizens'. I recalled it was Objects and now it's Functions, How come? Are functions promoted? J.
In programming language design, a first-class citizen (also object, entity, or value) in a given programming language is an entity which supports all the operations generally available to other entities. These operations typically include being passed as a parameter, returned from a function, and assigned to a variable. 
Another similar definition, 'First Class Citizens' of a programming language can be:

  1. can be stored in variables and data structures
  2. can be passed as a parameter to a subroutine
  3. can be returned as the result of a subroutine
  4. can be constructed at run-time
  5. has intrinsic identity (independent of any given name)
Java FCC are Objects: True
Scala FCC are Functions: ? (I may have to evaluate Scala to check the validity of 4 & 5).

Thursday, November 7, 2013

Evaluation strategies in Scala

What evaluation strategy does Scala follows? OR How does call by name and call by value evaluation strategies supported in Scala?

I would suggest reading wiki for understanding basics of evaluation strategies (http://en.wikipedia.org/wiki/Evaluation_strategy), specifically call by name and call by value, since both of these are supported in Scala. Below are the extracts which I found most useful:
Call by value
In call-by-value, the argument expression is evaluated, and the resulting value is bound to the corresponding variable in the function (frequently by copying the value into a new memory region). If the function or procedure is able to assign values to its parameters, only its local copy is assigned — that is, anything passed into a function call is unchanged in the caller's scope when the function returns.
Call by name
In call-by-name evaluation, the arguments to a function are not evaluated before the function is called — rather, they are substituted directly into the function body (using capture-avoiding substitution) and then left to be evaluated whenever they appear in the function. If an argument is not used in the function body, the argument is never evaluated; if it is used several times, it is re-evaluated each time it appears.
To understand this in Scala context, let's see this using an example. I have two version of AND implementation below:

Version 1
def and(x:Boolean, y: Boolean):Boolean =  if(x) y else false

Version 2
def and(x:Boolean, y: => Boolean):Boolean =  if(x) y else false

Both of these version returns the same result when called with different boolean values for x and y. Though both of these versions are different, version 2 pass y using 'call by name' strategy, represented by '=>' symbol.
You must be wondering, so now what is the difference? Let's introduce a loop function

def loop: Boolean = loop

Analyzing the outputs of the two statements will give a better understanding of the these strategies.

and(false, loop)

Version 1 shall fall into an infinite loop since it's following a call by value strategy. While with version 2 the statement shall work fine.

Courtesy: Martin Ordersky for explaining it so beautifully, I am spreading his word here.

Tuesday, November 5, 2013

Hello Scala

I want to head-start with Scala, how can I write hello world program in Scala?

I found multiple ways of getting started with Scala, downloaded the latest scala-eclipse IDE backed by JDK7. Below are the different ways to Hello Scala:

Via Scala object:

Create below Scala object & execute this as Scala application

package learn.scala
object Hello {
  def main(args: Array[String]): Unit = {
    println("world")
  }
}

Via Scala worksheet:

Create Scala worksheet with below statement and saving the file shall do the needful

package learn.scala
object HelloWorkSheet {
    println("Hello World")
}

I plan to sync my worksheet and keep this updated on GIST. Here's the link to my GIST(https://gist.github.com/ajjain/7364919)

Wednesday, October 2, 2013

Typesafe : Why are my heroes together?



Why are my heroes together? Looks like 'Renaissance is in Progress'

I stumbled upon Typesafe one day, don't know why? how? I reached there. I was surprised too see my heroes @ Typesafe leadership (http://www.typesafe.com/company/team). Post Sun, James & Post Spring, Rod, are they togeather with Martin for a new Renaissance? I am trying to understand the purpose of Typesafe.

Reactive programming is driving my attention. I am trying to understand what AKKA & Scala is? I am now restless to understand the functional programming paradigm. 

I have enrolled on Coursera on Functional Programming  (https://www.coursera.org/course/progfun) & Reactive Programming (https://www.coursera.org/course/reactive) classes.