Java Reference
In-Depth Information
Listing 2-10. Implicit Partial Function Application of String Concatenation
public static void main(String[] args) {
BiFunction<String, String, String> concat = (a,b) -> a + b;
greetFolks(whom -> concat.apply("Hello, ", whom));
}
public static void greetFolks(Function<String, String> greeter) {
for(String name : Arrays.asList("Alice", "Bob", "Cathy")) {
System.out.println(greeter.apply(name));
}
}
Listing 2-11. Explicit Partial Function Application of String Concatenation
public static void main(String[] args) {
BiFunction<String, String, String> concat = (a,b) -> a + b;
greetFolks(applyPartial(concat, "Hello, "));
}
public static <T,U,V> Function<U,V> applyPartial(
BiFunction<T,U,V> bif, T firstArgument
) {
return u -> bif.apply(firstArgument, u);
}
public static void greetFolks(Function<String, String> greeter) {
for(String name : Arrays.asList("Alice", "Bob", "Cathy")) {
System.out.println(greeter.apply(name));
}
}
Mr. Curry's Verb and Functional Shape
Partial function application acts on one function and takes another. Programming at the level of functions
like this is where “functional programming” got its name, and functional programming languages encourage
you to think at this level instead of at the level of data and instructions. Think of functional arguments as
voids in a jigsaw puzzle. Only a specific shape will fill that void. Every method you have access to is a piece
of that jigsaw puzzle, and they each have a shape. The shape of those methods is defined by the arguments
that they take and the arguments that they return. Like jigsaw puzzle pieces, you can also connect the shapes
together to make new shapes. Functional programming is the art of connecting the appropriate method
shapes together to fit the functional void.
For instance, the greetFolks method in Listing 2-10 and 2-11 provides a void with the shape of
String String: to call that method, we need to provide a function that takes a string and returns a string.
Unfortunately, we only had (String String) String: we only had a function that takes two strings as
arguments and returns a string. That shape does not quite fit. So what we did was partially apply the first
argument, which shaved that first argument off the shape of the method. This left us with a function with the
required shape of String String.
 
Search WWH ::




Custom Search