Google

May 13, 2014

Java 8 Currying tutorial

Currying (named after Haskell Curry) is the fact of evaluating function arguments one by one, producing a new function with one argument less on each step. Java 8 still does not have first class functions, but currying is “practically” possible with verbose type signatures, which is less than ideal. Here is a very simple example:


package com.java8.examples;

import java.util.function.Function;

public class CurryTest {
 
 public static void main(String[] args) {
  Function<Integer,Function<Integer,Integer>> add = (a) -> (b) -> a + b;
  
  Function<Integer,Integer> addOne = add.apply(1); 
  Function<Integer,Integer> addFive = add.apply(5);  
  Function<Integer,Integer> addTen = add.apply(10);  
  
  Integer result1 = addOne.apply(2); // returns 3
  Integer result2 = addFive.apply(2); // returns 7
  Integer result3 = addTen.apply(2); // returns 12
  
  System.out.println("result1 = "  + result1);
  System.out.println("result2 = "  + result2);
  System.out.println("result3 = "  + result3);
 
 }
}


The output will be:

result1 = 3
result2 = 7
result3 = 12

System.out.println(add.apply(1).apply(3)); // returns 4


If you want to add 3 numbers

Function<Integer,Function<Integer,Function<Integer, Integer>>> add = 
                                    (a) -> (b) -> (c) -> a + b + c;  
System.out.println(add.apply(1).apply(3).apply(5)); // returns 9



Note that the Function interface is in Java 8 API.


Now Currying in Pre Java 8 with anonymous inner classes

Define your own Function interface.

package com.currying;

public interface Function<A,B> {
     B apply (A a);
}



Provide the implementation class for Function with anonymous inner classes

package com.currying;

public class FunctionImpl implements Function<Integer, Integer> {
 
 @Override
 public Integer apply(Integer a) {
  return a;
 }
 
 public static Function<Integer, Function<Integer, Integer>> add() {
     return new Function<Integer, Function<Integer, Integer>>() {
         @Override
         public Function<Integer, Integer> apply(final Integer x) {
             return new Function<Integer, Integer>() {
                 @Override
                 public Integer apply(Integer y) {
                     return x + y;
                 }
             };
         }
     };
 }
   
 public static void main(String[] args) {
    System.out.println(add());                    //FunctionImpl object    
    System.out.println(add().apply(1));           //FunctionImpl object
    System.out.println(add().apply(1).apply(2));  //3
    System.out.println(add().apply(0).apply(2));  //2
 }

}


Output is:

com.currying.FunctionImpl$1@73d16e93
com.currying.FunctionImpl$1$1@659e0bfd
3
2


Tedious hey!!! compared to Java 8. It is even much easier in pure functional languages.

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home