Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Functional Programming In Java


Published on

Seminar about using Functional Programming ideas in Java

Published in: Technology, Self Improvement
  • Login to see the comments

Functional Programming In Java

  1. 1. Functional Programming in Java Java technology seminar SECR, 2007 Andrei Solntsev
  2. 2. Purpose S eminar gives an overview of Functional Programming methods and its applications in Java for coding Business Logic and its customization
  3. 3. Agenda <ul><li>FP overview </li></ul><ul><li>Sandwich algorithm </li></ul><ul><li>FP main features </li></ul><ul><li>Code samples </li></ul><ul><li>Business Logic with FP </li></ul><ul><li>FP libraries for Java </li></ul>
  4. 4. FP Overview Computation is executing statements to change the program state. Imperative programming Functional programming Computation is 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.
  5. 5. Sandwich algorithm Function createSandwich <ul><li>Take a bread </li></ul><ul><li>Spread bread with butter </li></ul><ul><li>Put cheese on the bread </li></ul><ul><li>return result </li></ul>Imperative return put ( cheese, spread(butter, bread) ) Functional
  6. 6. Sandwich algorithm If we want to use sausage instead of cheese ? Let’s pass sausage/cheese as input parameter No problems!
  7. 7. Sandwich algorithm <ul><li>Take a lower </li></ul><ul><li>Spread lower with middle </li></ul><ul><li>Put upper on the middle </li></ul><ul><li>return result </li></ul>Function createSandwich (lower, middle, upper) return put ( upper, spread(middle, lower) ) Function createSandwich (lower, middle, upper) No problems! bread butter sausage
  8. 8. Sandwich algorithm If we want to put butter instead of spreading ? Imperative programming: Problem! Functional programming: not a problem
  9. 9. Sandwich algorithm <ul><li>Take a lower </li></ul><ul><li>if mode = ‘put’ put middle on lower else spread middle on lower end if </li></ul><ul><li>Put upper on the middle </li></ul><ul><li>return result </li></ul>Procedure createSandwich (lower, middle, upper, mode) Imperative programming: Problem! bread butter sausage put Alternative: create 2 different functions  Code duplication
  10. 10. 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 <ul><li>spread </li></ul><ul><li>put </li></ul><ul><li>… </li></ul>createSandwich is a higher-order function which takes another function as a parameter
  11. 11. FP main features What is Functional Programming? <ul><li>Closures and higher order functions </li></ul><ul><li>Lazy evaluation </li></ul><ul><li>Recursion as a mechanism for control flow </li></ul><ul><li>Enforcement of referential transparency </li></ul><ul><li>No side-effects </li></ul>FP Languages <ul><li>Lisp (AutoCad) </li></ul><ul><li>Haskell, Scheme, Logo </li></ul><ul><li>XSLT </li></ul>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.
  12. 12. Code Samples in Haskell <ul><li>a dd :: I n teger -> Integer -> Integer </li></ul><ul><li>add  x y =  x + y </li></ul>functions inc :: Integer -> Integer inc = 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 ys zip   xs     ys     = [] Uncurried function F unction can be returned as a value ! Higher-order function curried function
  13. 13. Code Samples in Haskell <ul><li>ones = 1 : ones </li></ul>Infinite data structures numsFrom n = n : numsFrom (n+1) squares = map (^2) (numsfrom 0) take 5 squares => [0,1,4,9,16]
  14. 14. Code Samples in Haskell Fibonacci sequence fib = 1 : 1 : [ a+b | (a,b) <- zip fib (tail fib) ]
  15. 15. FP-Style code example in Java java.util.Properties Properties properties = new Properties(); properties.setProperty(“firstName&quot;, groom.getFirstName()); properties.setProperty(“lastName&quot;, groom.getLastName()); properties.setProperty(“salary&quot;, groom.getSalary()); return parameters; return Imperative Functional return new Properties() .setProperty(“firstName&quot;, groom.getFirstName()) .setProperty(“lastName&quot;, groom.getLastName()) .setProperty(“salary&quot;, groom.getSalary()); <ul><li>Pros </li></ul><ul><li>Cons </li></ul>
  16. 16. 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 <ul><li>Pros </li></ul><ul><li>Cons ? </li></ul>
  17. 17. FP: Pros and Cons Pros <ul><li>Reliable code </li></ul><ul><li>Readable </li></ul><ul><li>Reusable </li></ul><ul><li>… </li></ul><ul><li>Non-natural for human </li></ul><ul><li>Non-natural for computer </li></ul><ul><li>Performance </li></ul>Cons Example: Quick Sort algorithm
  18. 18. Code sample: Quicksort <ul><li>Quicksort in Haskell </li></ul><ul><li>qsort [] = [] </li></ul><ul><li>qsort (x:xs) = qsort elts_lt_x ++ </li></ul><ul><li>[x] ++ </li></ul><ul><li>qsort elts_greq_x </li></ul><ul><li>where </li></ul><ul><li>elts_lt_x = [y | y <- xs, y < x] </li></ul><ul><li>elts_greq_x = [y | y <- xs, y >= x] </li></ul>
  19. 19. Code sample: Quicksort <ul><li>qsort( a, lo, hi ) int a[], hi, lo; </li></ul><ul><li>{ </li></ul><ul><li>int h, l, p, t; </li></ul><ul><li>if (lo < hi) { </li></ul><ul><li>l = lo; h = hi; p = a[hi]; </li></ul><ul><li>do { </li></ul><ul><li>while ((l < h) && (a[l] <= p)) </li></ul><ul><li>l = l+1; </li></ul><ul><li>while ((h > l) && (a[h] >= p)) </li></ul><ul><li>h = h-1; </li></ul><ul><li>if (l < h) { </li></ul><ul><li>t = a[l]; a[l] = a[h]; a[h] = t; </li></ul><ul><li>} </li></ul><ul><li>} while (l < h); </li></ul><ul><li>t = a[l]; a[l] = a[hi]; a[hi] = t; </li></ul><ul><li>qsort( a, lo, l-1 ); </li></ul><ul><li>qsort( a, l+1, hi ); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>Quicksort in C
  20. 20. FP: Pros and Cons Pros <ul><li>Reliable code </li></ul><ul><li>Readable </li></ul><ul><li>Reusable </li></ul><ul><li>… </li></ul><ul><li>Non-natural for human </li></ul><ul><li>Non-natural for computer </li></ul><ul><li>Performance </li></ul>Cons Example: Quick Sort algorithm In Java, FP suits for implementing Business Logic Programs are easier to design, write and maintain, but programmer has less control over the machine.
  21. 21. 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 then Don’t check age
  22. 22. 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 function as parameter
  23. 23. 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); }
  24. 24. 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 = …; } Predefined values
  25. 25. 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 classes are often used as closures
  26. 26. 25 th frame 25 th frame
  27. 27. 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 ) {…} };
  28. 28. 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); } };
  29. 29. 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 );
  30. 30. 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); if (name != null && name.startsWith(“Mr.”)) { gentlemen .add(name); } } return gentlemen ; Imperative
  31. 31. 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.”
  32. 32. FP Applications: Transformers Transformer public interface Transformer { Object transform ( Object sourceObject ); } ListTransformer public class ListTransformer { public List transform ( List sourceList , Transformer transformer ); }
  33. 33. FP Applications: Transformers Given: list of Grooms Goal: create list grooms’ names List groomsNames = new ArrayList(); for (Iterator it = allGrooms .iterator(); it.hasNext(); ) { Groom groom = (Groom); groomsNames .add(groom.getName()); } return groomsNames ; Imperative
  34. 34. FP Applications: Transformers return ListTransformer. transform( allGrooms , new Transformer () { public Object transform(Object obj) { return ((Groom) obj).getName(); } } ) ; Functional Given: list of Grooms Goal: create list grooms’ names
  35. 35. 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 ); }
  36. 36. Business Logic customization 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>
  37. 37. Conclusion <ul><li>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. </li></ul>
  38. 38. FP Libraries for Java Commons Functors : Function Objects for Java JGA: Generic Algorithms for Java http://
  39. 39. Articles Functional programming in the Java language http :// Use recursion effectively in XSL Why Functional Programming Matters http:// Introduction to Haskell http://