Created
July 1, 2012 17:50
-
-
Save kakkun61/3029092 to your computer and use it in GitHub Desktop.
Functional Composition in Java ver. 1
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 implements Function { | |
@Override | |
public Function compose(final Function f) { | |
return new AbstractFunction() { | |
@Override | |
public double apply(double x) { | |
return AbstractFunction.this.apply(f.apply(x)); | |
} | |
}; | |
} | |
@Override | |
public abstract double apply(double 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 { | |
Function compose(Function f); | |
double apply(double 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 f = new AbstractFunction() { | |
@Override | |
public double apply(double x) { | |
return Math.exp(x); | |
} | |
}; | |
Function g = new AbstractFunction() { | |
@Override | |
public double apply(double x) { | |
return Math.pow(x, 2); | |
} | |
}; | |
Function h = new AbstractFunction() { | |
@Override | |
public double apply(double x) { | |
return -x+1; | |
} | |
}; | |
Function composed = f.compose(g).compose(h); | |
System.out.println(composed.apply(10)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment