Skip to content

Instantly share code, notes, and snippets.

@kakkun61
Created July 8, 2012 16:15
Show Gist options
  • Save kakkun61/3071573 to your computer and use it in GitHub Desktop.
Save kakkun61/3071573 to your computer and use it in GitHub Desktop.
Functional Composition in Java ver. 2
package functionalcomposition;
public abstract class AbstractFunction<Param, Result> implements Function<Param, Result> {
@Override
public <Param2> Function<Param2, Result> compose(final Function<Param2, Param> f) {
return new AbstractFunction<Param2, Result>() {
@Override
public Result apply(Param2 x) {
return AbstractFunction.this.apply(f.apply(x));
}
};
}
@Override
public abstract Result apply(Param x);
}
package functionalcomposition;
public interface Function<Param, Result> {
<Param2> Function<Param2, Result> compose(Function<Param2, Param> f);
Result apply(Param x);
}
package functionalcomposition;
public class Main {
public static void main(String[] args) {
Function<Double, Double> f = new AbstractFunction<Double, Double>() {
@Override
public Double apply(Double x) {
return Math.exp(x);
}
};
Function<Double, Double> g = new AbstractFunction<Double, Double>() {
@Override
public Double apply(Double x) {
return Math.pow(x, 2);
}
};
Function<Double, Double> h = new AbstractFunction<Double, Double>() {
@Override
public Double apply(Double x) {
return -x+1;
}
};
Function<Double, Double> composed = f.compose(g).compose(h);
System.out.println(composed.apply(10d));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment