1

I have this Python code that I found online and would like to know how to translate it to Java. My question is not about the algorithm but how to handle the function's arguments.

Here is the code:

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)

I would like to know what the function definition would look like. For example, a function returning y=x^2+3 would look like:

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

but

 return ternarySearch(f, leftThird, right, absolutePrecision)

is not working for me and I'd like to know what to do.

Update:

so for example i have y=3*x+2 it will be like this?

interface MyFunctor {
 int myFunction(int x);
}

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

like this?

1
  • 1
    I'm unable to parse basically anything but the code block. Could you (or someone w/ edit powers) please clean this up a bit so it resembles coherent English please? Commented May 20, 2010 at 14:13

1 Answer 1

8

In Java, there are no higher-order functions. That is, you can't pass a function as an argument to another function. What you can do is use the Command pattern; define an Interface supporting the method that you need, then pass an instance of that Interface implementing the method.

For example:

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)
}

and

interface MyFunctor {
  int myFunction(int arg);
}

and

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

Then you could call ternarySearch with an instance of MyFunctorImpl as the first argument.

Sign up to request clarification or add additional context in comments.

2 Comments

Great answer, though calling the method on MyFunctor apply or something similar might make it easier to understand.
Yeah, not knowing what the method is intended to do made it hard to come up with a descriptive method name. I assume if the OP understands the rest then he will know to change it accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.