interface pairfloatfunction { pair<float,float> calculate(int x); } interface floatfunction { float calculate(int x); } class sqrt implements pairfloatfunction { public pair<float, float> calculate(int x) { return new pair(-pow(x,0.5), pow(x,0.5)) } } class add_one implements floatfunction { public float calculate(int x) { return x + 1; } } i compose functions can perfom this:
add_one(sqrt(100)) = pair(-9,11) i understand need 'glue' functions together. stuck here, should writing method overload this?
class add_one { public float calculate(int x) { return x + 1; } public float calculate(pair pair) { pair.first += 1; pair.second += 1; return pair } } sorry new functional programming, there nice solution this?
based on code above, create generic interface responsible calculating.
interface calculation<t> { t calculate(int x); } this java 7 implementation, because did not specify java 8.
further explanation
the return type t generic; meaning implementation can return object type must consume integer x. make x parameter generic can decide function take parameter type.
note: static classes moved own class files , static modifier should removed. did consolidate sake of brevity.
full example
public class functional { static interface calculation<t> { t calculate(int x); } static class sqrt implements calculation<pair<float, float>> { public pair<float, float> calculate(int x) { float root = (float) math.pow(x, 0.5); return new pair<float, float>(-root, +root); } } static class addone implements calculation<float> { public float calculate(int x) { return (float) (x + 1); } } static <t> t calculate(int x, calculation<t> calculation) { return calculation.calculate(x); } public static void main(string[] args) { calculation<?>[] calculations = { new sqrt(), new addone() }; int x = 49; (calculation<?> calculation : calculations) { system.out.printf("%s: %s%n", calculation.getclass().getsimplename(), calculate(x, calculation)); } } static class pair<t, u> { private t val1; private u val2; public pair(t val1, u val2) { this.val1 = val1; this.val2 = val2; } protected t getval1() { return val1; } protected void setval1(t val1) { this.val1 = val1; } protected u getval2() { return val2; } protected void setval2(u val2) { this.val2 = val2; } @override public string tostring() { return "(" + val1 + ", " + val2 + ")"; } } } output
sqrt: (-7.0, 7.0) addone: 50.0
Comments
Post a Comment