5.7 Generic Functions (.NET, C#, CSharp, VB, Visual Basic, F#)
NMath provides convenience methods for applying unary and binary functions to elements of a vector. Each of these methods takes a function delegate. The Apply() method returns a new vector whose contents are the result of applying the given function to each element of the vector. The Transform() method modifies a vector object by applying the given function to each of its elements. For example, assuming MyFunc is a function that takes a double and returns a double:
Code Example – C# vector
var v = new DoubleVector ( 10, 0, -1 ); // Construct a delegate for MyFunc Func<double, double> MyFuncDelegate = new Func<double, double>( MyFunc ); // Construct a new vector whose values are the result of applying // MyFunc to the values in vector v. v remains unchanged. DoubleVector w = v.Apply( MyFuncDelegate ); // Transform the contents of v. v.Transform( MyFuncDelegate ); v == w; // true!
Code Example – VB vector
Dim V As New DoubleVector(10, 0, -1) ' Construct a delegate for MyFunc Dim MyFuncDelegate As New Func(Of Double, Double)(AddressOf MyFunc) ' Construct a new vector whose values are the result of applying ' MyFunc to the values in vector v. v remains unchanged. Dim W As DoubleVector = V.Apply(MyFuncDelegate) ' Transform the contents of v. V.Transform(MyFuncDelegate) V = W ' true!
NMath provides delegates for many commonly used math functions in the NMathFunctions class.