2

I read the next answer about passing function as parameter.

Still, I don't get the idea. My function can get any function: sin(x), cos(x), etc.

As I understood, I can create an interface, for example:

public interface functionI<T> {

}

that would wrap It.

Now I have my function:

    public void needToDo(functionI<Integer> a, int x0Par, int hPar){
}

(needToDo, for example, need to substitue the x of the function n x0par and hPar, and find the Max. If I got sin(x), I need to find the max of sin(x0Par) and (sin(hPar)).

I didn't understand how I use it in my function. How will I know what to do when I got the function, that can be anything (polynomial, sin(x), and so on)

2
  • 3
    Your interface doesn't currently have any methods, which is a bit of a problem... and we don't know what needToDo is meant to be achieving, either... Commented Dec 24, 2011 at 9:08
  • see this post stackoverflow.com/questions/2186931/… Commented Dec 24, 2011 at 9:12

2 Answers 2

5

Something like this:

public interface Function1<RESULT,INPUT> {
    RESULT call(INPUT input);
}

public class Sin implements Function1<Double,Double> {
    public static final Sin instance = new Sin();
    private Sin() {
    }
    public Double call(Double x) {
        return Math.sin(x);
    }
}

public Double needToDo(Function1<Double,Double> aFunction, Double x0Par, Double hPar) {
   Double d1 = aFunction.call(x0Par);
   Double d2 = aFunction.call(hPar);
   return d1 > d2 ? d1 : d2;
}

public static void main(String[] args) {
    Double x0Par = 10.2;
    Double hPar = 1.9;
    Double ret = needToDo(Sin.instance, x0Par, hPar);
    System.out.println(ret);
}
Sign up to request clarification or add additional context in comments.

Comments

3

It doesn't quite work like that; you cannot pass arbitrary functions as parameters in Java, instead you pass objects which have specific, often generic sounding, functions.

So you could define a MathOperation interface, which has an execute method, taking a double and returning a double.

public interface MathOperation {
  double execute(double x);
}

and then you can create

public class Sin implements MathOperation {
  public double execute(double x) { return Math.sin(x); }
}

and have a function that uses it like

public void needToDo(MathOperation op, double x) {
  System.out.println(op.execute(x));
}

You could create an on-the-fly function for needToDo like

...
needToDo(new MathOperation() {
    public double execute(double x) { return x * 2.0; }
});
...

But you can't pass Math.sin as a parameter. There are reflection tricks you can do, but that's another issue.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.