Sorry for the longer snippets of code, but I wanted to demonstrate the various options available to you using lambdas and anonymous functions.
First we will create some basic functions to play with ...
'Solves a basic linear equation y(x) = ax + b, given a, b, and x. Function Linear(a As Double, b As Double, x As Double) As Double Return a * x + b End Function 'Return the inverse of a number (ie y(x) = -x) Function Inverse(x As Double) As Double Return -x End Function
And a function that takes a function.
'To help differentiate the type of the parameter from the return type, 'I'm being generic with the return type. This function takes any function 'that takes a double and returns some generic type, T. Public Function EvalEquation(Of T)(x As Double, equation As Func(Of Double, T)) As T Return equation(x) End Function
And finally, we will use it!
'The closest thing to a functor is probably the AddressOf keyword. For x = 0 To 10 Dim answer = EvalEquation(x, AddressOf Inverse) 'Do something Next
But AddressOf has some limitations ... EvalEquationForX expects a function that takes only one parameter, so I cannot just use AddressOf, since I cannot pass additional parameters. However, I can dynamically create a function that can do this for me.
For x = 0 To 10 Dim answer = EvalEquation(x, Function(x) Dim a = 1 Dim b = 0 Return Linear(a, b, x) End Function) 'Do something Next
I should note that you can define Func(Of T1, T2, T3, T4,... TResult)
so that you can create a function that could take two parameters and use them instead.
Public Function EvalEquationWithTwoParameters(Of T)( a As Double, b As Double, x As Double, equation As Func(Of Double, Double, Double, T)) As T Return equation(a, b, x) End Function
And use it as follows:
For x = 0 To 10 Dim answer = EvalEquationWithTwoParameters(1, 0, x, AddressOf Linear) 'Do something Next
Hope this helps!