Home > Blockchain >  Can i use Lambda Expression in jdk8,Implement a generic function to calculate way
Can i use Lambda Expression in jdk8,Implement a generic function to calculate way

Time:06-22

Like this

1.f(x,y)=ax by
2.f(x,y,z)= ax by cz
3.f(2x,2y) = ax^2 by^2 
....
4.f(2x,y,3z,4m,5n) = ax^2 by cz^3 dm^4 en^5 

My idea is as follows this java method named myFun()()()

1.myFun(x,y)(1,2)(3,4) = x 2y = 3 8 = 11
2.myFun(x,y)(1,2,3)(1,1,1) = x 2y 3z = 1 2 3=6
....

I konw Y combination operator,and Currying,but i don't know how to use in java,If can't, I can do it in python?

CodePudding user response:

Try this.

interface F { double apply(double x, double y); }
interface G { F apply(double a, double b); }

G myFunc = (a, b) -> (x, y) -> a * x   b * y;
System.out.println(myFunc.apply(1, 2).apply(3, 4));

output:

11.0

CodePudding user response:

I believe this is what you want.

  • create a BiFunction that returns a lambda which takes x and y and applies the subsequent lambda to xx and yy.
BiFunction<Integer,Integer, IntBinaryOperator> fn1 = (x,y)-> (xx,yy)-> x*xx   y*yy;
int result = fn1.apply(1,2).applyAsInt(3,4);
System.out.println(result);

prints

11

Both the BiFunction and IntBinaryOperator are Functional interfaces in the java.util.function package. To use more variables, one has to define new functional interfaces.


interface TriFunction<S,T,U,V> {
    V apply(S arg1, T arg2, U arg3);
}

interface IntTrinaryOperator {
    int applyAsInt(int ar1,int arg2, int arg3);
}

Then declare the result as before.


TriFunction<Integer,Integer, Integer,IntTrinaryOperator> fn2 = (x,y,z)-> (xx,yy,zz)-> x*xx   y*yy   z*zz;
int result2 = fn2.apply(1,2,3).applyAsInt(1,1,1);
System.out.println(result2);

prints

6

Update

As long as you are using primitive types as the arguments you can use the ... notation to allow different number of arguments.

interface IntNaryOperator {
    int applyAsInt(int...a);
}

interface NFunction<R> {
    R apply(int...s);
}

NFunction<IntNaryOperator> fn3 = (int[] a)->(int[] b)-> {
                  
                  int sum = 0;
                  for (int i = 0;i < a.length; i  ) {
                      sum  = (a[i]*b[i]);
                  }
                  return sum;
};

int sum  = fn3.apply(1,2,3,4,5,6,7).applyAsInt(1,2,3,4,5,6,7);
System.out.println(sum);

prints

140

If generic arrays are used it is possible to pollute the heap. The method names can of course be changed to whatever makes sense for you. And you may want to verify that the supplied argument counts are the same or you could get an ArrayIndexOutOfBoundsException.

  • Related