Monday 31 July 2017

2. Lambda Expressions


1. What is a Functional Programing?
  1. Characteristics of FP
    1. Function Closure Support.
    2. Higher-order functions
    3. Use of recursion as a mechanism for flow control
  2. Examples of FP languages : scala, erlang, LISP, clojure.
  3. Examples of FP code
Function powerFunctionFactory(int power) {
  int powerFunction(int base) {
      return pow(base, power);
  }
  return powerFunction;
}
Function square = powerFunctionFactory (2);
square(3); // returns 9
Function cube = powerFunctionFactory (3);
cube(3); // returns 27
  1. FP supports closures (closure is a method reference or anonymous function).
  2. FP supports currying ‘->’( Given a function foo(x,y) which results in the value of z, better expressed foo(x,y) -> z)


2. What is a Closure?
  1. When you declare a local variable, that variable has a scope. Generally local variables exist only within the block or function in which you declare them.
function() {
 var a = 1;
 console.log(a); // works
}    
console.log(a); // fails
  1. If I try to access a local variable, most languages will look for it in the current scope, then up through the parent scopes until they reach the root scope.
var a = 1;
function() {
 console.log(a); // works
}    
console.log(a); // works
  1. a closure is the ability for a function to access variables defined in the same execution scope as the function is defined.
var a = "hello";
var f1 = function(){
   print (a);
}
a = "man";
f1();    // will result to "man";
  1. A closure is a persistent scope which holds on to local variables even after the code execution has moved out of that block.


3. What is a Higher-order functions?
  1. Higher-order function is a function that does at least one of the following:
    1. takes one or more functions as arguments (i.e., procedural parameters)
    2. returns a function as its result.
  2. Example of Higher-order function
Takes one or more functions as arguments
var proveIt = function() {
 alert("you triggered " + this.id);
};

document.getElementById("clicker").addEventListener("click", proveIt);


Returns a function as its result
outer = function() {
 var a = 1;
 var inner = function() {
   console.log(a);
 }
 return inner; // this returns a function
}

var fnc = outer(); // execute outer to get inner
fnc();


4. Examples of Functional Programing and Object Oriented Programing?


Java 7 (OOP)
Java 8 (FP & OOP)
Thread thread = new Thread(new Runnable() {
   @Override
   public void run(){
       System.out.println("Task #1 is running");
   }
});
thread.start();
// Lambda Runnable
Runnable r = () -> { System.out.println("Task #2 is running"); };
// start the thread
new Thread(r).start();

5. Why Lambda Expression?

  1. Java lambda expressions are Java's first step into functional programming.
  2. A Java lambda expression is thus a function which can be created without belonging to any class.
  3. A lambda expression can be passed around as if it was an object and executed on demand.
  4. Simple to write, easy to understand.
  5. Passing a lambda expression to another function allow us to pass not only values but also behaviors and this enable to dramatically raise the level of our abstraction and then project more generic, flexible and reusable API.

6. What is Anonymous class?
  1. Anonymous classes enable you to make your code more concise.
  2. They enable you to declare and instantiate a class at the same time.
  3. They are like local classes except that they do not have a name.Use them if you need to use a local class only once.
  4. While local classes are class declarations, anonymous classes are expressions, which means that you define the class in another expression.
interface HelloWorld {
       public void greet();
       public void greetSomeone(String someone);
}



HelloWorld frenchGreeting = new HelloWorld() {

           String name = "tout le monde";
           public void greet() {
               greetSomeone("tout le monde");
           }
           public void greetSomeone(String someone) {
               name = someone;
               System.out.println("Salut " + name);
         }
};

  1. Syntax of Anonymous Classes :
The syntax of an anonymous class expression is like the invocation of a constructor, except that there is a class definition contained in a block of code.
HelloWorld frenchGreeting = new HelloWorld() { ……………… };

  1. The anonymous class expression consists of the following:
    1. The new operator
    2. The name of an interface to implement or a class to extend. In this example, the anonymous class is implementing the interface HelloWorld.
    3. Parentheses that contain the arguments to a constructor, just like a normal class instance creation expression. Note: When you implement an interface, there is no constructor, so you use an empty pair of parentheses, as in this example.
    4. A body, which is a class declaration body. More specifically, in the body, method declarations are allowed but statements are not.
7. What is Lambda expression?
  1. One issue with anonymous classes is that if the implementation of your anonymous class is very simple, such as an interface that contains only one method, then the syntax of anonymous classes may seem unwieldy and unclear.
  2. If interface contains only one method, then also we need to mention the method name in anonymous class declaration.
interface Runnable {
       public void run();
}



Runnable runnable = new Runnable() {
           public void run() {
               System.out.println(“i am a new thread”);
           }
 };

  1. In above example, i am creating an implementation class (anonymous class) of Runnable interface, but still i need to mention method name ‘run()’.
  2. In this case by using lambda expression, we can directly pass functionality as an argument to another method to treat functionality as method argument, or code as data.
interface Runnable {
       public void run();
}



Runnable runnable = () ->  System.out.println(“i am a new thread”);

  1. We can use lambda expression, if the interface contains only one method.
  2. A lambda expression can be passed around as if it was an object and executed on demand.

8. Syntaxes of Lambda expressions
  1. Lambda expressions supports interfaces only, Creating an instance to implementation class of a functional interface (interface contains only one method).
  2. Suppose java.lang.Runnable interface is a functional interface, it contains only one method called ‘run()’.
  3. We can assign a block of code or method without a name to variable of type interface directly by using lambda expressions.
          Runnable runnable = () -> {
               System.out.println(“i am a new thread”);
           };
  1. Block of code contains syntax like this  :       
    (arguments list)  ->  { block of code };
  2. In lambda expression, no need to mention the name of the block.
  3. We can pass the list of arguments with or without data type mentioning.
  1. But recommended way is don’t mention data type, java compiler will detect the data type of the argument by looking into the functional interface.
  2. Suppose if we mention wrong data type (other than data type declared in interface method) it will give compile time error.
  3. It will also not consider inheritance relationship also, we need to mention exact type, not child type or not parent type, otherwise don’t mention any type it will add type.
  1. Java compiler automatically detects argument types and return type of the lambda expression.
  2. No need to mention the return statement also, by default it returns last statement.
  3. If you write last statement as improper, it gives compile time error.
  1. If you want we can also mention return statement, but it is optional to mention, but if you mention return statement need to write ‘{ }‘ code only.

  1. If block contains only one line of code than optional to use ‘{‘.

9. Rules for Lambda expressions
  1. We can create anonymous class for an interface or abstract class or class with any number of methods, but lambda expressions can only supports functional interfaces(interface contains only one method).
ANONYMOUS CLASS






LAMBDA EXPRESSION
*Lambda expressions for abstract classes and classes it is giving error.
  1. We need to mention a correct data type or don’t mention the data type, just declare a variable, compiler automatically add data type to that variables.




=
  1. Some examples of lambda expression
MyInterface myInterface = (a) -> {return a.indexOf('i');}
MyInterface myInterface = (a, b ) -> a+b;
MyInterface myInterface = (a) -> a*b;
MyInterface myInterface = (int a, int b ) -> a+b;
MyInterface myInterface = (int a, int b ) -> {
        return a+b;
};
  1. If you mentioned any data type for one argument, you need to mention remaining args also.



3. Java Program to create Binary Tree