1

How can you count the number of parameters while initializing a variadic function/lambda expression? Or: how can you determine the arity of a lambda-expression?

Example:

public class MathFunction{

  private java.util.function.Function <double[], Double> function = null;
  private int length = 0;

  public MathFunction ( Function <double[], Double> pFunction ){    
    this.function = pFunction;
    this.length = ???
  }
}

Now, if you init a new MathFunction like this,

MathFunction func = new MathFunction((x) -> Math.pow(x[0], x[1]));

how can you count the passed parameters (here: two) in the MathFunction-constructor ?

Tunaki
  • 132,869
  • 46
  • 340
  • 423
user1511417
  • 1,880
  • 3
  • 20
  • 41
  • You could try longer and longer arrays until an `ArrayIndexOutOfBoundsException` is not caught. This would be insane though. The sane way is just to pass the length as a separate argument. – Paul Boddington Nov 12 '15 at 12:27

1 Answers1

3

You can't.

MathFunction declares a constructor that takes a single parameter, which is a Function. This function will operate on a double array and return a Double. But note that this function can operate on any double arrays, of any length.

There is no way the function can know the length of the array: it only knows that it can operate on a double array, whatever its length.

Consider these lambdas:

x -> Math.pow(x[0], x[1])
x -> Math.pow(x[0], x[1]) + x[2]
x -> x[0]

They all valid lambdas, all of them complies to the same Function<double[], Double> and all of them (would) operate on an array of different lengths.

Your only solution would be to pass the length of the array to the constructor as a second argument.

public MathFunction ( Function <double[], Double> pFunction, int length ){    
    this.function = pFunction;
    this.length = length;
}

By the way, this is not called arity, this term refer to variable arguments.

Community
  • 1
  • 1
Tunaki
  • 132,869
  • 46
  • 340
  • 423