functional programming in java
DESCRIPTION
Seminar about using Functional Programming ideas in JavaTRANSCRIPT
![Page 1: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/1.jpg)
Functional Programming
in JavaJava technology seminar
SECR, 2007Andrei Solntsev
![Page 2: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/2.jpg)
Purpose
Seminar gives an overview of
Functional Programming methodsand
its applications in Java for
coding Business Logicand
its customization
![Page 3: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/3.jpg)
Agenda
FP overview Sandwich algorithm FP main features Code samples Business Logic with FP FP libraries for Java
![Page 4: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/4.jpg)
FP Overview
Computationis executing statements to change the program state.
Imperative programming
Functional programming
Computationis evaluation of expressions
The focus is on what, not how
Expressions are formed by using functions to combine basic values
Program consists of a sequence of commands.
![Page 5: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/5.jpg)
Sandwich algorithm
Function createSandwich
1. Take a bread2. Spread bread with butter3. Put cheese on the bread4. return result
Imperative
return put ( cheese,spread(butter, bread) )
Functional
![Page 6: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/6.jpg)
Sandwich algorithm
If we want to use sausage instead of cheese ?
Let’s pass sausage/cheese as input parameter
No problems!
![Page 7: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/7.jpg)
Sandwich algorithm
1. Take a lower2. Spread lower with middle3. Put upper on the middle4. return result
Function createSandwich (lower, middle, upper)
return put ( upper,spread(middle, lower) )
Function createSandwich (lower, middle, upper)
No problems!
bread butter sausage
![Page 8: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/8.jpg)
Sandwich algorithm
If we want to put butter instead of spreading ?
Imperative programming: Problem!
Functional programming: not a problem
![Page 9: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/9.jpg)
Sandwich algorithm
1. Take a lower2. if mode = ‘put’
put middle on lower else
spread middle on lower end if
3. Put upper on the middle4. return result
Procedure createSandwich (lower, middle, upper, mode)
Imperative programming: Problem!
bread butter sausage put
Alternative: create 2 different functions Code duplication
![Page 10: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/10.jpg)
Sandwich algorithm
return put ( upper,action(middle, lower) )
Function createSandwich (lower, middle, upper, action)
Functional programming: not a problem
bread butter sausage put
Action is a function with 2 parameters
• spread• put• …
createSandwich is a higher-order function which takesanother function as a parameter
![Page 11: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/11.jpg)
FP main features
What is Functional Programming?
• Closures and higher order functions
• Lazy evaluation
• Recursion as a mechanism for control flow
• Enforcement of referential transparency
• No side-effects
FP Languages
• Lisp (AutoCad)
• Haskell, Scheme, Logo
• XSLT
Where a traditional imperative program might use a loop to traverse a list, a functional style would often use a higher-order function, map, that takes as arguments a function and a list, applies the function to each element of the list, and returns a list of the results.
![Page 12: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/12.jpg)
Code Samples in Haskell
add :: Integer -> Integer -> Integeradd x y = x + y
functions
inc :: Integer -> Integerinc = add 1
map :: (a->b) -> [a] -> [b]map f [] = []map f (x:xs) = f x : map f xs
zip (x:xs) (y:ys) = (x,y) : zip xs yszip xs ys = []
Uncurriedfunction
Function can bereturned as a value !
Higher-orderfunction
curriedfunction
![Page 13: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/13.jpg)
Code Samples in Haskell
ones = 1 : ones
Infinite data structures
numsFrom n = n : numsFrom (n+1)
squares = map (^2) (numsfrom 0)
take 5 squares => [0,1,4,9,16]
![Page 14: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/14.jpg)
Code Samples in Haskell
Fibonacci sequence
fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
![Page 15: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/15.jpg)
FP-Style code example in Java
java.util.Properties
Properties properties = new Properties();properties.setProperty(“firstName", groom.getFirstName());properties.setProperty(“lastName", groom.getLastName());properties.setProperty(“salary", groom.getSalary());return parameters;
return
Imperative
Functional
return new Properties() .setProperty(“firstName", groom.getFirstName()) .setProperty(“lastName", groom.getLastName()) .setProperty(“salary", groom.getSalary());• Pros
• Cons
![Page 16: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/16.jpg)
FP-Style code example In Java
StringBuffer
StringBuffer sb = new StringBuffer();sb.append(“a”);sb.append(“b”);sb.append(“c”);return sb.toString();
return new StringBuffer() .append(“a”); .append(“b”); .append(“c”) .toString();
Imperative
Functional
• Pros • Cons ?
![Page 17: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/17.jpg)
FP: Pros and Cons
Pros
• Reliable code• Readable• Reusable• …
• Non-natural for human• Non-natural for computer• Performance
Cons
Example: Quick Sort algorithm
![Page 18: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/18.jpg)
Code sample: Quicksort
Quicksort in Haskell
qsort [] = []
qsort (x:xs) = qsort elts_lt_x ++
[x] ++
qsort elts_greq_x
where
elts_lt_x = [y | y <- xs, y < x]
elts_greq_x = [y | y <- xs, y >= x]
![Page 19: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/19.jpg)
Code sample: Quicksort
qsort( a, lo, hi ) int a[], hi, lo;{
int h, l, p, t;if (lo < hi) {
l = lo; h = hi; p = a[hi];do {
while ((l < h) && (a[l] <= p))l = l+1;
while ((h > l) && (a[h] >= p))h = h-1;
if (l < h) {t = a[l]; a[l] = a[h]; a[h] = t;
}} while (l < h);
t = a[l]; a[l] = a[hi]; a[hi] = t;qsort( a, lo, l-1 );qsort( a, l+1, hi );
}}
Quicksort in C
![Page 20: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/20.jpg)
FP: Pros and Cons
Pros
• Reliable code• Readable• Reusable• …
• Non-natural for human• Non-natural for computer• Performance
Cons
Example: Quick Sort algorithm
In Java, FP suits for implementingBusiness Logic
Programs are easier to design, write and maintain, butprogrammer has less control over the machine.
![Page 21: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/21.jpg)
Business logic with FP
GroomFilter
List suitableGrooms = new ArrayList();
for (groom in allGrooms){ if (minAge > -1 && groom.getAge() < minAge)
continue;
if (maxAge > -1 && groom.getAge() > maxAge)continue;
suitableGrooms.add(groom);}
return suitableGrooms;
List filterGrooms(List allGrooms, int minAge, int maxAge)
If age is -1 thenDon’t check age
![Page 22: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/22.jpg)
Business logic with FP
GroomFilter
List suitableGrooms = new ArrayList();
for (groom in allGrooms){ if (groomChecker.accept(groom))
suitableGrooms.add(groom);}
return suitableGrooms;
List filterGrooms(List allGrooms, Filter groomChecker)
Pass functionas parameter
![Page 23: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/23.jpg)
Business logic with FP
public interface Filter { /** * Method defines whether given object is accepted. * @param obj any Object * @return true iff object is accepted */ boolean accept(Object obj);}
![Page 24: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/24.jpg)
Business logic with FP
public interface Filter { boolean accept(Object obj);
public static final Filter ACCEPT = new Filter() {
public boolean accept(Object obj){return true;} };
public static final Filter NOT_NULL = new Filter() {
public boolean accept(Object obj){return obj!=null;} };
public static final Filter NEGATE ..; public static final Filter IS_NULL = …;}
Predefinedvalues
![Page 25: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/25.jpg)
Business logic with FP
Client 1
List suitableGrooms grooms = GroomFilter.filterGrooms(…, new Filter() {
public boolean accept(Object obj){ return ((Groom) obj).getAge() > 23;}
});
Client 2
List suitableGrooms = GroomFilter.filterGrooms(…,Filter.ACCEPT);
Closure – object representing a function
Anonymous classesare often used as closures
![Page 26: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/26.jpg)
25th frame
25th frame
![Page 27: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/27.jpg)
Parameterized Closures
StringFilter
public class StringFilter implements Filter{ public static startsWith(final String prefix) {
return new Filter{ public boolean accept(Object o){
return ((String) o).startsWith(prefix); }};
}
public static endsWith (final String postfix) {…} public static contains (final String substring) {…} public static matches (final String regexp) {…}};
![Page 28: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/28.jpg)
Composition of functions
Composition of functions: AND
public class AND implements Filter{ public AND (Filter filter1, Filter filter2) {
this.filter1 = filter1;this.filter2 = filter2;
}
public boolean accept(Object obj) {
return filter1.accept(obj) && filter2.accept(obj);
}};
![Page 29: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/29.jpg)
FP Applications: Filters
FilteredIterator
public class FilteredIterator implements Iterator{ public FilteredIterator(Iterator iterator, Filter filter);}
CollectionsUtils
static List collectList(Iterator it);static Set collectSet(Iterator it);static List filterList (List original, Filter filter);static Set filterSet (Set originalSet, Filter filter);
![Page 30: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/30.jpg)
FP Applications: Filters
Given: a list of all grooms’ names.Goal: find all names with prefix “Mr.”
List gentlemen = new LinkedList();
for (Iterator it = groomsNames.iterator(); it.hasNext(); ){ String name = (String) it.next(); if (name != null &&
name.startsWith(“Mr.”)) {
gentlemen.add(name); }}
return gentlemen;
Imperative
![Page 31: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/31.jpg)
FP Applications: Filters
Functional
return CollectionsUtils.filterList(allGrooms,StringFilter.startsWith(“Mr.”));
Given: a list of all grooms’ names.Goal: find all names with prefix “Mr.”
![Page 32: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/32.jpg)
Transformer
public interface Transformer{ Object transform(Object sourceObject);}
ListTransformer
public class ListTransformer{ public List transform(List sourceList, Transformer transformer);}
FP Applications: Transformers
![Page 33: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/33.jpg)
FP Applications: Transformers
Given: list of GroomsGoal: create list grooms’ names
List groomsNames = new ArrayList();
for (Iterator it = allGrooms.iterator(); it.hasNext(); ){ Groom groom = (Groom) it.next(); groomsNames.add(groom.getName());}
return groomsNames;
Imperative
![Page 34: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/34.jpg)
FP Applications: Transformers
return ListTransformer.transform( allGrooms,
new Transformer(){ public Object transform(Object obj) {
return ((Groom) obj).getName(); }});
Functional
Given: list of GroomsGoal: create list grooms’ names
![Page 35: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/35.jpg)
Business Logic customization
Example using Plexus container
import org.codehaus.plexus.embed.Embedder;
public List findSuitableGrooms(Client woman){
Filter clientGroomFilter = (Filter) embedder.lookup( “groomFilter”, woman.getName());
return GroomFilter.filterGrooms(allGrooms, clientGroomFilter);
}
![Page 36: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/36.jpg)
META-INF/plexus/components.xml
<component-set> <components> <component> <role>groomFilter</role> <role-hint>default</role-hint> <implementation>examples.Filter.ACCEPT</implementation> </component>
<component> <role>groomFilter</role> <role-hint>Maril Strip</role-hint> <implementation>examples.filters.OlderThan25</implementation> </component>
<component> <role>groomFilter</role> <role-hint>Jenifer Lopez</role-hint> <implementation>examples.filters.SalaryBiggerThan10000</implementation> </component>
</components></component-set>
Business Logic customization
![Page 37: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/37.jpg)
Conclusion
I hope this article has provided you with a good foundation for incorporating closures and higher order functions into your Java code, as well as giving you a glimpse of the beauty and effectiveness of functional programming.
![Page 38: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/38.jpg)
FP Libraries for Java
Commons Functors: Function Objects for Javahttp://jakarta.apache.org/commons/sandbox/functor
JGA: Generic Algorithms for Java http://jga.sourceforge.net
http://plexus.codehaus.org
![Page 39: Functional Programming In Java](https://reader036.vdocuments.net/reader036/viewer/2022062405/5550f4cab4c90501448b46a0/html5/thumbnails/39.jpg)
Articles
Functional programming in the Java languagehttp://www-128.ibm.com/developerworks/library-combined/j-fp.html
Use recursion effectively in XSLhttp://www-128.ibm.com/developerworks/xml/library/x-xslrecur
Why Functional Programming Mattershttp://www.math.chalmers.se/~rjmh/Papers/whyfp.html
Introduction to Haskellhttp://www.haskell.org/tutorial/