Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function composition in Java

I'm trying to implement a lazy sequence (meaning that the next item is only calculated when you invoke the step function), and one of the methods it should have is "map" which receives a function that affects all the members.
The most elegant way to do this is to use function composition, and assign the new function to the function variable, but since functions are not first class values in Java I have no idea how to do this.

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 of map(map(map(stepFunction()))) ("map" in this case being the function given through the method "map").

like image 427
EpsilonVector Avatar asked Nov 19 '09 20:11

EpsilonVector


3 Answers

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());
    }
}
like image 118
Jonathan Feinberg Avatar answered Oct 07 '22 21:10

Jonathan Feinberg


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).

like image 45
Kevin Bourrillion Avatar answered Oct 07 '22 19:10

Kevin Bourrillion


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.

like image 1
bmargulies Avatar answered Oct 07 '22 19:10

bmargulies