Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 1 FP Part II

Download as pdf or txt
Download as pdf or txt
You are on page 1of 18

Chapter One

Functional Programming- Part Two

1
Functional Programming
 What is Functional Programming
 It is a programming paradigm:- it is a programming
pattern which need to be followed in the functional
programming standard
 All you deal with hear is function
 Rooted form Mathematics
• Specifically based on Lambda Calculus
 It is language independent
• It can be applied in many programming languages
• Not specific language X supports functional programming
 In OOP – we deal with objects and classes where in
Functional programming we deal with functions alone

2
Constraints in Functional Programming
1. It should be a pure function
These functions have two main properties
• First, they always produce the same output for same
arguments irrespective of anything else
• Second they have no side effects i.e. they do not modify
any argument or global variables or output
2. Recursion
• There are no “for” or “while” loop in functional
language
• Iteration in functional language is implemented through
recursion
• Usually we use for, while to apply iteration but in FP,
iteration is implemented using recursion
• However, it is hardly to implement it in java, therefore
java 8 simply apply major features of FP
3
Constraints in Functional Programming
3. Referential Transparency
• You don’t have assignment statement inside your
functional expression
• In FP variables one defined, they do not change their
value throughout the program
• FP don’t have assignment statements
4. Function are first class and can be higher order
• First class functions re treated as first class variable
• The first class variables can be passed to functions as
parameter, can be returned from functions or stored in
data structure
• High order functions are the functions that take other
functions as arguments and they can also return
functions
• Functions can also take object, or variable of primitive
type as an argument 4
Constraints in Functional Programming
5. Variables are Immutable
• In FP, the values of variables which you forward to functional
programming, can’t be changed after it has been initiated
• We can create new variables but we can’t modify existing
variables, and this really helps to maintain state throughout
the run time of a program
• You can’t make it as mutable data
• All variables in functional programming are to be treated as
immutable data
• Immutable data:- the value for the variable can’t be changed
• Once we create a variable and set its value, we can have full
confidence knowing that the value of that variable will never
change
• Therefore, Functional programming treats computation as the
evaluation of mathematical functions which avoids changing
state and Mutable Data
5
Functional Programming
Example
Variable = (x) -> x+1; //assign it to a variable
add()
{
return (x)->x+1; // return function as values
}
add(Var)
{
add((x)->x+1);// pass function as Arguments
}

6
Summary of Functional Programming
 FP- becomes useful to have a way to write a function
without necessarily having to give it a name(i.e. without
having a separate declaration)
 This is exactly what the “ Abstraction” syntax is in the
lambda calculus does
 As a result, many languages including java that
implements first class functions refer to anonymous
function( functions without an explicit named
declarations) as lambda expression

7
Disadvantages and Apps of Functional Interface
Disadvantages
• Sometimes writing pure functions can reduce the readability of
code
• Writing program in recursive style instead of using loops can be
bit intimidating
• Writing pure functions are easy but combining them with rest of
application and I/O operations is the difficult task
• Immutable values and recursion can lead to decrease in
performance
Applications
• It is used in mathematical computations like big data
• It is needed where Concurrency or parallelism code is required
programming languages that support functional programming
e.g. Haskell, Javascript, Scale, Erlarg, Lisp, ML, Clojure, Ocaml..
• Whatsapp – needs only 50 engineers for its 900M users b/c
Erlarg is used to implement its concurrency needs
• Face book- uses Haskell in its anti-spam system
Lambda Expression
Lambda Expression: (Functional programming Style)
• Are anonymous functions- a way of representing functions
• Insatiate interface with a single method
• The interface must carry only one abstract single method
• Replace more variable verbose(too many line of code,
unwanted redundant code) class declaration
• Way to create set of function composition methods
• Function composition is an operation that takes two functions f
and g and produce a function h: h(x) = g(f(x))
Where to use Lambda Expression
N.B
• Lambda expression can only appear in places where they will
• be assigned to a variable whose type is a functional interface
• You want a single instance of an inner class that implements
• interface
• (The expected type must be an interface that has exactly one
abstract method)
Different ways of writing Lambdas
• One linear lambda expression
• Multi linear lambda expression
• Lambda expression with arguments
• Lambda expression with arguments with type interface
• Lambda expression with arguments and return type
What is Functional Interface?
• An interface which contains only a single Abstract method
Example
public interface Circle
{
public abstract void calculateArea(double r);
}
What is Lambda Expression?
• It is the one which provides a short cut syntax to implement the
method of functional interfaces
Syntax
• (arg1, arg2, …. argN)->{ method body };
• Classic approach to implementing an interface in java before
Lambda Expression which is added in java 8, are the
following two possible syntaxes
1. Declaring a class
2. Using Anonymous inner class
Implementation of Functional Interface
@Functional Interface
public interface Circle
{
public abstract void calculateArea(double r);
}

How to implement a functional interface without using lambda expression


1. Define a class that implement the Circle interface
2. Override the calculateArea(double r) method in that class
3. Create an object reference of the Circle interface
4. Create an object of the CircleImpl class and then assign it to object
reference created in step 3
5. Finally execute the claculateArea() method on that object reference
Implementation of Functional Interface
How to implement a functional interface by using Lambda expression
1. Create an object reference of the Circleinterface
2. Define a lambda expression and assign it to reference of Circle
interface
3. Finally execute the Calculate Area ( ) method on that object
reference
Parts of Lambda Expression
Syntax
There are 3 parts in a lambda expression
(arg1, arg2, …. argN) -> { method body;};

Part 1 - syntax, (arg1, arg2, …. argN) -> { method body;};


e.g. (double radius) -> { method body;};
Part 2 – syntax, (arg1, arg2, …. argN) -> { method body;};
-> an arrow pointer, connects the method body and the argument
Part 3 – syntax, (arg1, arg2, …. argN) -> { method body;};
e.g. ( )-> {System.out.println(“Hello World”); };
Functional interface annotation
Functional interface annotation
@Functional interface
Used to restrict someone to add additional abstract
methods
• This annotation is used to declare that an interface is a
functional interface
• If we use this annotation to declare a functional
interface, and if we add more than one abstract method
in that interface it results in compilation failure
Few built in functional interface
Function, Bifunction, Cosumer, Biconsumer, Predicate,
Bipredicate supplier,
Example1
Paymentprocessor interface , processpayment( ) method
Package LamdaDemo;
@Functional Interface
public interface paymentprocessor
{
public abstract void processpayment( String paymentmode);
}
Example1…
Create an other class Output
Package LambdaDemo;
Payment done via debit card
public class paymentLambda
{
public static void main(String[] args) Payment done via credit card
{
payment processor p1=(paymentmode)->
{
if(paymentmode.equals(“Debit Card”))
System.out.println(“Payment done via debitcard”);
else if(paymentmode.equals(“Credit Card”))
System.out.println(“Payment done via Credit card”);
};
p1.processpayment(“Debit Card”);
System.out.println( );
p1.processpayment(“Credit Card”);
}
}
Example2
Net salary Calculator interface- calculate NetSalary( ) method
Package LambdaDemo;
@FunctionalInterface
public interface NetSalaryCalculator
{
public abstract void CalculateNetSalary(int gross salary, int deduction);
}
Create new class salary lambda
Package LambdaDemo;
public class SalaryLambda
{
public static void main(String[ ] args)
{
NetSalaryCalculator ns1 = (grosssalary, deduction)->
{ System.out.println(“NetSalary=”+ (grosssalary-deduction));};
ns1. CalculateNetSalary(10000, 500);
}
} 18
Exercise
• Write a java Functional program that calculate GPA of a
student for one semester

19

You might also like