By user855


2011-05-26 05:54:48 8 Comments

I was wondering if there is any way to pull that in Java. I think it is not possible without native support for closures.

15 comments

@Ajeet 2019-01-22 05:11:27

Yes, I agree with @Jérôme, curring in Java 8 is not supported in a standard way like in Scala or other functional programming languages.

public final class Currying {
  private static final Function<String, Consumer<String>> MAILER = (String ipAddress) -> (String message) -> {
    System.out.println(message + ":" + ipAddress );
  };
  //Currying
  private static final Consumer<String> LOCAL_MAILER =  MAILER.apply("127.0.0.1");

  public static void main(String[] args) {
      MAILER.apply("127.1.1.2").accept("Hello !!!!");
      LOCAL_MAILER.accept("Hello");
  }
}

@Jose Luis Soto Posada 2018-10-14 00:55:59

The advantage of using Currying in Java 8 is that it lets you define high order functions and then pass a first order function and function arguments in a chained, elegant way.

Here is an example for Calculus, the derivative function.

  1. Lets define the derivative function approximation as (f(x+h)-f(x))/h. This will be the high order function
  2. Let's calculate the derivative of 2 different functions, 1/x, and the standardized gaussian distribution

1

    package math;

    import static java.lang.Math.*;
    import java.util.Optional;
    import java.util.function.*;

    public class UnivarDerivative
    {
      interface Approximation extends Function<Function<Double,Double>, 
      Function<Double,UnaryOperator<Double>>> {}
      public static void main(String[] args)
      {
        Approximation derivative = f->h->x->(f.apply(x+h)-f.apply(x))/h;
        double h=0.00001f;
        Optional<Double> d1=Optional.of(derivative.apply(x->1/x).apply(h).apply(1.0)); 
        Optional<Double> d2=Optional.of(
        derivative.apply(x->(1/sqrt(2*PI))*exp(-0.5*pow(x,2))).apply(h).apply(-0.00001));
        d1.ifPresent(System.out::println); //prints -0.9999900000988401
        d2.ifPresent(System.out::println); //prints 1.994710003159016E-6
      }
    }

@Rishabh Agarwal 2018-04-12 17:03:23

Yes, see the code example for yourself:

import java.util.function.Function;

public class Currying {

    private static Function<Integer, Function<Integer,Integer>> curriedAdd = a -> b -> a+b ;

    public static void main(String[] args) {

        //see partial application of parameters
        Function<Integer,Integer> curried = curriedAdd.apply(5);
        //This partial applied function can be later used as
        System.out.println("ans of curried add by partial application: "+ curried.apply(6));
        // ans is 11

        //JS example of curriedAdd(1)(3)
        System.out.println("ans of curried add: "+ curriedAdd.apply(1).apply(3));
        // ans is 4

    }

}

This is simple example with curriedAdd being a curried function which returns another function, and this can be used for partial application of parameters as stored in curried which is a function in itself. This is now later applied fully when we print it on screen.

Moreover, later you can see how you can use it in kind of JS style as

curriedAdd.apply(1).apply(2) //in Java
//is equivalent to 
curriedAdd(1)(2) // in JS

@Ahmed Adel Ismail 2018-03-25 00:10:54

This is a library for currying and partial application in Java :

https://github.com/Ahmed-Adel-Ismail/J-Curry

It also supports destructuring Tuples and Map.Entry into method parameters, like for example passing a Map.Entry to a method that takes 2 parameters, so the Entry.getKey() will go to the first parameter, and the Entry.getValue() will go for the second parameter

More details in the README file

@John Lee 2017-11-14 06:09:45

An another choice is here for Java 6+

abstract class CurFun<Out> {

    private Out result;
    private boolean ready = false;

    public boolean isReady() {
        return ready;
    }

    public Out getResult() {
        return result;
    }

    protected void setResult(Out result) {
        if (isReady()) {
            return;
        }

        ready = true;
        this.result = result;
    }

    protected CurFun<Out> getReadyCurFun() {
        final Out finalResult = getResult();
        return new CurFun<Out>() {
            @Override
            public boolean isReady() {
                return true;
            }
            @Override
            protected CurFun<Out> apply(Object value) {
                return getReadyCurFun();
            }
            @Override
            public Out getResult() {
                return finalResult;
            }
        };
    }

    protected abstract CurFun<Out> apply(final Object value);
}

then you could achieve currying by this way

CurFun<String> curFun = new CurFun<String>() {
    @Override
    protected CurFun<String> apply(final Object value1) {
        return new CurFun<String>() {
            @Override
            protected CurFun<String> apply(final Object value2) {
                return new CurFun<String>() {
                    @Override
                    protected CurFun<String> apply(Object value3) {
                        setResult(String.format("%s%s%s", value1, value2, value3));
//                        return null;
                        return getReadyCurFun();
                    }
                };
            }
        };
    }
};

CurFun<String> recur = curFun.apply("1");
CurFun<String> next = recur;
int i = 2;
while(next != null && (! next.isReady())) {
    recur = next;
    next = recur.apply(""+i);
    i++;
}

// The result would be "123"
String result = recur.getResult();

@Natix 2016-12-08 18:25:34

One more take on the Java 8 possibilities:

BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;

Function<Integer, Integer> increment = y -> add.apply(1, y);
assert increment.apply(5) == 6;

You can also define utility methods like this one:

static <A1, A2, R> Function<A2, R> curry(BiFunction<A1, A2, R> f, A1 a1) {
    return a2 -> f.apply(a1, a2);
}

Which gives you an arguably more readable syntax:

Function<Integer, Integer> increment = curry(add, 1);
assert increment.apply(5) == 6;

@Rogério 2013-02-07 11:45:58

Java 8 (released March 18th 2014) does support currying. The example Java code posted in the answer by missingfaktor can be rewritten as:

import java.util.function.*;
import static java.lang.System.out;

// Tested with JDK 1.8.0-ea-b75
public class CurryingAndPartialFunctionApplication
{
   public static void main(String[] args)
   {
      IntBinaryOperator simpleAdd = (a, b) -> a + b;
      IntFunction<IntUnaryOperator> curriedAdd = a -> b -> a + b;

      // Demonstrating simple add:
      out.println(simpleAdd.applyAsInt(4, 5));

      // Demonstrating curried add:
      out.println(curriedAdd.apply(4).applyAsInt(5));

      // Curried version lets you perform partial application:
      IntUnaryOperator adder5 = curriedAdd.apply(5);
      out.println(adder5.applyAsInt(4));
      out.println(adder5.applyAsInt(6));
   }
}

... which is quite nice. Personally, with Java 8 available I see little reason to use an alternative JVM language such as Scala or Clojure. They provide other language features, of course, but that's not enough to justify the transition cost and the weaker IDE/tooling/libraries support, IMO.

@Michael Easter 2015-02-21 16:03:22

I'm impressed with Java 8, but Clojure is a compelling platform beyond functional language features. Clojure offers highly efficient, immutable data structures and sophisticated concurrency techniques such as software-transactional memory.

@Korny 2015-03-09 09:14:00

Thanks for the solution, not so much for the language dig :) Weaker IDE support is an issue, but tooling/libraries is not clear cut - having gone back to Java 8 after Clojure, I'm really missing tools midje, libraries like core.async, and language features like macros and easy functional syntax. The currying example in clojure: (def adder5 (partial + 5)) (prn (adder5 4)) (prn adder5 6)

@Rogério 2015-03-09 15:17:49

Clojure may be a great language, but the problem is that it's just too "alien" for the majority of Java developers that are only used to conventional C-style syntax; it's very hard to see a significant migration to Clojure (or any other alternative JVM language) in the future, specially considering that several such languages already exist for many years and it hasn't happened (the same phenomenon occurs in the .NET world, where languages like F# remain marginal).

@zinking 2015-09-30 02:49:13

which is still ugly and probably just for fun

@M4ks 2016-06-27 13:02:35

I have to downvote, because it shows simple case. Try one which from String makes your own class which then converts to some other class, and compare the amount of code

@Rogério 2016-06-27 18:00:34

@M4ks The question is only whether Java supports currying or not, it's not about the amount of code when compared to other languages.

@Jose Romero 2016-10-27 06:33:59

Actually there are plenty of reasons not to use Java: Less code legibility, primitives' mess, no pattern matching, no case classes, no real closures, verbosity, no default parameters, no type inference, no implicit values, not immutable by default, and immutable is normally by reference and not by structure, no good concurrency model, no literal definition of tuples, etc, etc. If you can choose, go for Scala. If you can't, well Java 8 is not thaaaaaaaat bad.

@Rogério 2016-10-27 15:28:33

If I could choose (and face it, the reality is that we almost always have little or no say in such matters) I would go with Kotlin, a much more developer-friendly language than "academic"-friendly Scala (or at least that's my perception).

@kouretinho 2017-01-19 14:23:17

excellent, concise explanation

@John McClean 2015-06-11 17:05:28

There are a lot of options for Currying with Java 8. Function type Javaslang and jOOλ both offering Currying out of the box (I think this was an oversight in the JDK), and Cyclops Functions module has a set of static methods for Currying JDK Functions and method references. E.g.

  Curry.curry4(this::four).apply(3).apply(2).apply("three").apply("4");

  public String four(Integer a,Integer b,String name,String postfix){
    return name + (a*b) + postfix;
 }

'Currying' is also available for Consumers. E.g to return a method with 3 params, and 2 of those already applied we do something similar to this

 return CurryConsumer.curryC3(this::methodForSideEffects).apply(2).apply(2);

Javadoc

@Xaerxess 2011-05-26 06:06:36

EDIT: As of 2014 and Java 8, functional programming in Java is now not only possible, but also not ugly (I dare to say beautiful). See for example Rogerio's answer.

Old answer:

Java isn't best choice, if you are going to use functional programming techniques. As missingfaktor wrote, you will have to write quite big amount of code to achieve what you want.

On the other hand, you are not restricted to Java on JVM - you can use Scala or Clojure which are functional languages (Scala is, in fact, both functional and OO).

@Thomas Darimont 2014-06-11 18:46:46

One can emulate currying with Java 7 MethodHandles: http://www.tutorials.de/threads/java-7-currying-mit-methodhandles.392397/

import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;

public class MethodHandleCurryingExample {
    public static void main(String[] args) throws Throwable {
        MethodHandles.Lookup lookup = MethodHandles.lookup();
        MethodHandle sum = lookup.findStatic(Integer.class, "sum", MethodType.methodType(int.class, new Class[]{int.class, int.class}));
        //Currying
        MethodHandle plus1 = MethodHandles.insertArguments(sum,0,1);
        int result = (int) plus1.invokeExact(2);
        System.out.println(result); // Output: 3
    }
}

@Konrad 'ktoso' Malawski 2013-09-21 21:33:30

Well, Scala, Clojure or Haskell (or any other functional programming language...) are definitely THE languages to use for currying and other functional tricks.

Having that said is certainly possible to curry with Java without the super amounts of boilerplate one might expect (well, having to be explicit about the types hurts a lot though - just take a look at the curried example ;-)).

The tests bellow showcase both, currying a Function3 into Function1 => Function1 => Function1:

@Test
public void shouldCurryFunction() throws Exception {
  // given
  Function3<Integer, Integer, Integer, Integer> func = (a, b, c) -> a + b + c;

  // when
  Function<Integer, Function<Integer, Function<Integer, Integer>>> cur = curried(func);

  // then
  Function<Integer, Function<Integer, Integer>> step1 = cur.apply(1);
  Function<Integer, Integer> step2 = step1.apply(2);
  Integer result = step2.apply(3);

  assertThat(result).isEqualTo(6);
}

as well as partial application, although it's not really typesafe in this example:

@Test
public void shouldCurryOneArgument() throws Exception {
  // given
  Function3<Integer, Integer, Integer, Integer> adding = (a, b, c) -> a + b + c;

  // when
  Function2<Integer, Integer, Integer> curried = applyPartial(adding, _, _, put(1));

  // then
  Integer got = curried.apply(0, 0);
  assertThat(got).isEqualTo(1);
}

This is taken from a Proof Of Concept I've just implemented for fun before JavaOne tomorrow in an hour "because I was bored" ;-) The code is available here: https://github.com/ktoso/jcurry

The general idea could be expanded to FunctionN => FunctionM, relatively easily, though "real typesafety" remains a problem for the partia application example and the currying example would need a hell lot of boilerplaty code in jcurry, but it's doable.

All in all, it's doable, yet in Scala it's out of the box ;-)

@Andreas_D 2011-05-26 06:55:43

Currying requires to return a function. This is not possible with java (no function pointers) but we can define and return a type that contains a function method:

public interface Function<X,Z> {  // intention: f(X) -> Z
   public Z f(X x);
}

Now let's curry a simple division. We need a Divider:

// f(X) -> Z
public class Divider implements Function<Double, Double> {
  private double divisor;
  public Divider(double divisor) {this.divisor = divisor;}

  @Override
  public Double f(Double x) {
    return x/divisor;
  }
}

and a DivideFunction:

// f(x) -> g
public class DivideFunction implements Function<Double, Function<Double, Double>> {
  @Override
  public function<Double, Double> f(Double x) {
    return new Divider(x);
  }

Now we can do a curried division:

DivideFunction divide = new DivideFunction();
double result = divide.f(2.).f(1.);  // calculates f(1,2) = 0.5

@Andreas_D 2011-05-26 07:02:59

Now that I've finished my example (developed from scratch) it turns out, that the only difference to missingcodes answer is that I don't use anonymous classes ;)

@missingfaktor 2011-05-26 10:04:26

It's missingfaktor, not missingcodes.

@Andreas_D 2011-05-26 10:49:57

@missingfaktor - mea culpa ;)

@Peter Lawrey 2011-05-26 06:30:20

While you can do Currying in Java, it is ugly (because its not supported) In Java is it simpler and faster to use plain loops and simple expressions. If you post an example of where you would use currying, we can suggest alternatives which do the same thing.

@missingfaktor 2011-05-26 06:43:46

What does currying have got to do with loops?! At least look up the term before you answer a question about it.

@Peter Lawrey 2011-05-26 06:46:36

@missingFaktor, curried functions are usually applied to collections. e.g. list2 = list.apply(curriedFunction) where curriedFunction might be 2 * ? In Java you would do this with a loop.

@missingfaktor 2011-05-26 06:48:33

@Peter: That's partial application, not currying. And neither is specific to collection operations.

@Peter Lawrey 2011-05-26 06:51:18

@missingfaktor, My point is; not to get hung up on a specific feature but take a step back and look at the wider problem and there is very likely to be a simple solution.

@missingfaktor 2011-05-26 06:53:05

@Peter: If you want to question the point of the question, you should post your remark as a comment, and not as an answer. (IMHO)

@Peter Lawrey 2011-05-26 06:55:43

@missingfaktor, You are right, but in my case I wanted to give what I believe is the answer in Java to the real problem which is to use the techniques which work well in Java.

@missingfaktor 2011-05-26 06:00:08

Currying and partial application is absolutely possible in Java, but the amount of code required will probably turn you off.


Some code to demonstrate currying and partial application in Java:

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

interface Function2<A, B, C> {
  public C apply(final A a, final B b);
}

class Main {
  public static Function2<Integer, Integer, Integer> simpleAdd = 
    new Function2<Integer, Integer, Integer>() {
      public Integer apply(final Integer a, final Integer b) {
        return a + b;
      }
    };  

  public static Function1<Integer, Function1<Integer, Integer>> curriedAdd = 
    new Function1<Integer, Function1<Integer, Integer>>() {
      public Function1<Integer, Integer> apply(final Integer a) {
        return new Function1<Integer, Integer>() {
          public Integer apply(final Integer b) {
            return a + b;
          }
        };
      }
    };

  public static void main(String[] args) {
    // Demonstrating simple `add`
    System.out.println(simpleAdd.apply(4, 5));

    // Demonstrating curried `add`
    System.out.println(curriedAdd.apply(4).apply(5));

    // Curried version lets you perform partial application 
    // as demonstrated below.
    Function1<Integer, Integer> adder5 = curriedAdd.apply(5);
    System.out.println(adder5.apply(4));
    System.out.println(adder5.apply(6));
  }
}

FWIW here is the Haskell equivalent of above Java code:

simpleAdd :: (Int, Int) -> Int
simpleAdd (a, b) = a + b

curriedAdd :: Int -> Int -> Int
curriedAdd a b = a + b

main = do
  -- Demonstrating simpleAdd
  print $ simpleAdd (5, 4)

  -- Demonstrating curriedAdd
  print $ curriedAdd 5 4

  -- Demostrating partial application
  let adder5 = curriedAdd 5 in do
    print $ adder5 6
    print $ adder5 9

@missingfaktor 2011-05-26 06:11:16

@OP: Both are executable code snippets and you can try them out at ideone.com.

@Juliet 2011-06-02 20:49:14

Such ugly java code. +1, you've earned it.

@Adam Arold 2012-05-08 08:36:45

This answer deserves an accept.

@Matthias Braun 2014-03-22 10:23:00

This answer is outdated since the release of Java 8. See Rogério's answer for a more concise way.

@Jérôme Verstrynge 2011-05-26 06:02:56

Currying a method is always possible in Java, but it does not support it in a standard way. Trying to achieve this is complicated and makes the code pretty unreadable. Java is not the appropriate language for this.

Related Questions

Sponsored Content

60 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

80 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

15 Answered Questions

[SOLVED] What is 'Currying'?

64 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3803073 View
  • 3232 Score
  • 64 Answer
  • Tags:   java random integer

31 Answered Questions

[SOLVED] When to use LinkedList over ArrayList in Java?

20 Answered Questions

[SOLVED] Does Java support default parameter values?

42 Answered Questions

[SOLVED] "implements Runnable" vs "extends Thread" in Java

46 Answered Questions

[SOLVED] Does a finally block always get executed in Java?

54 Answered Questions

[SOLVED] Creating a memory leak with Java

25 Answered Questions

[SOLVED] Reading a plain text file in Java

  • 2011-01-17 18:29:13
  • Tim the Enchanter
  • 2231154 View
  • 875 Score
  • 25 Answer
  • Tags:   java file-io ascii

Sponsored Content