Created
July 8, 2012 16:15
-
-
Save kakkun61/3071573 to your computer and use it in GitHub Desktop.
Functional Composition in Java ver. 2
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
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); | |
} |
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
package functionalcomposition; | |
public interface Function<Param, Result> { | |
<Param2> Function<Param2, Result> compose(Function<Param2, Param> f); | |
Result apply(Param x); | |
} |
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
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