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;
}
}
我想组成函数,以便可以执行以下操作:
ADD_ONE(SQRT(100)) = Pair(-9,11)
我了解我需要将功能“粘合”在一起。
但是我被困在这里,是否应该编写另一种方法重载呢?
class ADD_ONE {
public Float calculate(int x) {
return x + 1;
}
public Float calculate(Pair pair) {
pair.first += 1;
pair.second += 1;
return pair
}
}
抱歉,我是函数编程的新手,对此有没有好的解决方案?
最佳答案
根据上面的代码,我将创建一个通用接口来负责计算。
interface Calculation<T> {
T calculate(int x);
}
这是Java 7的实现,因为您没有指定Java 8。
进一步说明
返回类型
T
是通用的;意味着您的实现可以返回任何Object
类型,但必须使用整数x
。您甚至可以使x
参数成为通用参数,以便您可以决定将哪个函数用作参数类型。注意:静态类将被移到其自己的类文件中,并且应删除static修饰符。为了简洁起见,我这样做只是为了巩固所有内容。
完整的例子
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;
for (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 + ")";
}
}
}
输出量
Sqrt: (-7.0, 7.0)
AddOne: 50.0