Lambda Expression Parameters/declaration

226 views Asked by At

I have been signed up for a while and don't usually post unless I really cannot find an answer, and now, I feel quite stuck.

I have only recently started getting familiarized with java Lambda expressions (mainly the function ones) such as BinaryOperator and Bifunction..) I was looking at the sources for these and I see you declare them as, for example:

public interface BiFunction<T, U, R> {...}.

So it seems to me that there is no way to dynamically create an interface (similar to BiFunction) but with a number of parameters and 'equation' set during runtime.

I will give a practical example which I think will explain much better the type of problem I would like to solve:

Lets say I wanted to make a program where the user could input a mathematical function and evaluate it in a point. To begin, lets assume it is a one variable function so:

Function<Integer,Integer> f1 = (x) -> Math.pow(x,2);

would be a solution to the problem, except that I am defining the function f(x) = x^2 before runtime. I would like to know if there is a way to create a function during runtime asking the user which function they would like to enter.

This problem could then be complicated more if the user can enter equations with multiple parameters.

Thanks for any help.

Max

1

There are 1 answers

1
user268396 On BEST ANSWER

What you need for this is currying. Given a function f which takes parameters a, b and c you can define a curried version of f which takes parameter a and spits out a function g which takes parameters b and c. Continue the currying process and you will have only 3 cases of arity to worry about:

  1. Zero arguments. Invoke the function.
  2. One argument. Invoke the function with the given parameter.
  3. Two arguments or more. Curry the function, and re-evaluate because the curried function will have a reduced arity.

So if you want to use lambda's you need to define a lambda which curries a function. Of course you also probably need to define relevant operators for whatever algebra's you'd like to support during runtime but that is probably a fixed symbol table (and can probably be defined likewise as a hastable of functions/lambdas taking arguments).