vb.netfunctionlambdaparamarray

How to define a function as the sum of all functions in ParraArray in VB.NET


I have a VB.NET function as follows:

Public Function Equilibrium(ParamArray F() As Func(Of Double, Double)) As Boolean

  'I would like to define a function
  ' G(x) = sum of all F(x) 
End Function

The parameters of the function are an array of functions F() that takes a double and returns a double. I would like to define a function G(x as Double) as Double inside the above function as the sum of all F(x), but what I've tried so far gave me syntax errors. Could anyone please help me? Greatly appreciated.


Solution

  • This seems to work, see if that is what you have thought of...

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim f As New List(Of Func(Of Double, Double))
        f.Add(AddressOf fTest)
        f.Add(AddressOf fTest)
        f.Add(AddressOf fTest)
        Dim b As Boolean = Equilibrium(f.ToArray)
    End Sub
    
    Public Function fTest(value As Double) As Double
        Return Math.PI * value
    End Function
    
    Public Function Equilibrium(ParamArray F() As Func(Of Double, Double)) As Boolean
        Dim input As Double = 2.38
        Dim G As Func(Of Double, Double) =
            Function(v As Double) As Double
                Return (From fItem As Func(Of Double, Double) In F
                        Select fItem(v)).Sum
            End Function
        Dim sum As Double = G(input)
        ' ...
    End Function