Last active
July 26, 2019 02:44
-
-
Save ayago/8ae6ad74602963e81a946893a806563b to your computer and use it in GitHub Desktop.
Partial Application in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.Function; | |
import static java.lang.String.format; | |
class SamplePartialApplication { | |
public static void main(String[] args) { | |
Fx2<Integer, Integer, Integer> add = (x, y) -> x + y; | |
System.out.println(format("Fully applied function of 2 arity result: %s", add.apply(2, 3))); | |
Function<Integer, Integer> addTwo = PartialApplication.partial(add, 2); | |
System.out.println(format("Partially applied 2 to function of two arity: %s", addTwo.apply(3))); | |
Fx3<Integer, Integer, String, String> descriptiveAdd = (x, y, z) -> z + (x + y); | |
Fx2<Integer, String, String> firstPartialDescribe = PartialApplication.partial(descriptiveAdd, 2); | |
Function<String, String> describe5 = PartialApplication.partial(firstPartialDescribe, 3);; | |
System.out.println(describe5.apply("The result is: ")); | |
Function<String, String> alternativeDescribe5 = PartialApplication.partial(descriptiveAdd, 2, 3); | |
System.out.println(alternativeDescribe5.apply("Alternative result is: ")); | |
} | |
/** | |
* Function with arity of 2 | |
* @param <I1> type of first input | |
* @param <I2> type of second input | |
* @param <O> type of output | |
*/ | |
@FunctionalInterface | |
public interface Fx2<I1, I2, O> { | |
/** | |
* Execute this function | |
* @param inputOne first input | |
* @param inputTwo second input | |
* @return output of this function | |
*/ | |
O apply(I1 inputOne, I2 inputTwo); | |
} | |
/** | |
* Function with arity of 3 | |
* @param <I1> type of first input | |
* @param <I2> type of second input | |
* @param <I3> type of third input | |
* @param <O> type of output | |
*/ | |
@FunctionalInterface | |
public interface Fx3<I1, I2, I3, O> { | |
/** | |
* Execute this function | |
* @param inputOne first input | |
* @param inputTwo second input | |
* @param inputThree third input | |
* @return output of this function | |
*/ | |
O apply(I1 inputOne, I2 inputTwo, I3 inputThree); | |
} | |
public static class PartialApplication { | |
public static <I1, I2, O> Function<I2, O> partial(Fx2<I1, I2, O> f, I1 inputOne) { | |
return i2 -> f.apply(inputOne, i2); | |
} | |
public static <I1, I2, I3, O> Function<I3, O> partial(Fx3<I1, I2, I3, O> f, I1 inputOne, I2 inputTwo) { | |
return i3 -> f.apply(inputOne, inputTwo, i3); | |
} | |
public static <I1, I2, I3, O> Fx2<I2, I3, O> partial(Fx3<I1, I2, I3, O> f, I1 inputOne) { | |
return (i2, i3) -> f.apply(inputOne, i2, i3); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment