Function composition in Java
I'm trying to implement a lazy sequence (meaning that the next item is only calculated when you invoke开发者_C百科 the step function), and one of the methods it should have is "map
" which receives a function that affects all the members.
I thought about having a class that only contains a function, as a sort of "function pointer" wrapper, but I don't see how that can be used for composition.
Edit: question is homework related.
Also, it should be able to handle multiple compositions along the lines ofmap(map(map(stepFunction())))
("map
" in this case being the function given through the method "map").Welcome to Java and its pains.
interface Function<T> {
public T eval(T argument);
}
class Lazy<T> {
private Iterator<T> source;
private Function<T> filter;
Lazy(final Iterator<t> source, final Function<T> filter) {
this.source = source;
this.filter = filter;
}
public T step() {
return filter.eval(source.next());
}
}
Google Collections has the Function
type, the Functions.compose(Function, Function)
method, the Iterables.transform(Iterable, Function)
method, and much more.
Not helpful to you if this is for homework (I really wish everyone would disclose when their question is homework-related).
In Java, you always do this with a class protocol. See java.lang.Thread
and the run function for the canonical example. There are no 'function pointers' or 'function variables' in Java.
FWIW, the "function pointer" equivalent in Java is an interface with a single method. You implement the interface with some class, which provides an implementation of the method, and then store a reference to that class object.
Changing the reference to another class object, which implements the method differently, is equivalent to changing the function pointer to point to a different function.
Java 8 added the java.util.function
package, wich make possible to do what the original question asked (https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html):
Function<Integer, Integer> multiply = (value) -> value * 3;
Function<Integer, Integer> add = (value) -> value + 2;
Function<Integer, Integer> addThenMultiply = multiply.compose(add);
Integer result1 = addThenMultiply.apply(3);
System.out.println(result1); // 15
Still it's not really super nice, but this is using both composition and laziness as requested in the question...
public static <T> void apply(final List<T> list, final Function<T> func)
{
for(final T val : list)
{
func.perform(val);
}
}
interface Function<T>
{
void apply(T value);
}
class DisplayFunction<T>
implements Function<T>
{
public void perform(T value)
{
System.out.println(value);
}
}
the call apply(list, new DisplayFunction());
精彩评论