如何在Java中实现此Python代码段?

时间:2010-05-20 14:09:09

标签: java python function

我有这个在线发现的Python代码,想知道如何将它翻译成Java。我的问题不是算法,而是如何处理函数的参数。

以下是代码:

def ternarySearch(f, left, right, absolutePrecision):
    #left and right are the current bounds; the maximum is between them
    if (right - left) < absolutePrecision:
        return (left + right)/2

    leftThird = (2*left + right)/3
    rightThird = (left + 2*right)/3

    if f(leftThird) < f(rightThird):
        return ternarySearch(f, leftThird, right, absolutePrecision)

    return ternarySearch(f, left, rightThird, absolutePrecision)

我想知道函数定义是什么样的。例如,返回y=x^2+3的函数看起来像:

public static int y(int x){
 return x*x+3;
}

但是

 return ternarySearch(f, leftThird, right, absolutePrecision)

不适合我,我想知道该怎么做。

更新

所以例如我有y = 3 * x + 2它会是这样吗?

interface MyFunctor {
 int myFunction(int x);
}

class MyFunctorImpl implements MyFunctor {
  int myFunction(int  x) {
      return 3*x+2
  }
}
像这样?

1 个答案:

答案 0 :(得分:8)

在Java中,没有高阶函数。也就是说,您不能将函数作为参数传递给另一个函数。你可以做的是使用命令模式;定义支持所需方法的接口,然后传递实现该方法的接口实例。

例如:

int ternarySearch(MyFunctor f, int left, int right, float absolutePrecision) {
  #left and right are the current bounds; the maximum is between them
  if (right - left) < absolutePrecision:
    return (left + right)/2

  leftThird = (2*left + right)/3
  rightThird = (left + 2*right)/3

  if (f.myFunction(leftThird) < f.myFunction(rightThird)) {
    return ternarySearch(f, leftThird, right, absolutePrecision)
  }
  return ternarySearch(f, left, rightThird, absolutePrecision)
}

interface MyFunctor {
  int myFunction(int arg);
}

class MyFunctorImpl implements MyFunctor {
  int myFunction(int arg) {
     // implementation
  }
}

然后,您可以使用ternarySearch的实例作为第一个参数调用MyFunctorImpl