Search code examples
f#math.netmathnet-numerics

How can I convert an F# (double -> double) to Func<double, double>?


I'm using MathNet.Numerics.LinearAlgebra to build a library. I need to apply a user-specified function to every element of the matrix, for which I know I can use Map:

open System
open MathNet.Numerics.LinearAlgebra
open MathNet.Numerics.LinearAlgebra.Double

let m1 = matrix [[1.0; 2.0; 3.0]]
let f1 = fun s -> s * 3.14
let m2 = m1.Map f1 // THIS FAILS
let m3 = m1.Map (fun s -> s * 3.14) // THIS WORKS!

In the line for m2 I get the following error:

This expression was expected to have type Func<float, 'a> but here has type double -> double

But I need to be able to pass in the mapping function instead of defining it inline as for m3. The documentation for MathNet.Numerics does not seem to have an answer to my problem.


Solution

  • You can construct the delegate like this:

    let m2 = m1.Map (Func<_, _> f1)
    

    F# implicitly constructs delegates in some cases, as seen with the lambda in the question, but it's not always seamless. See the MSDN page for delegates in F# for some additional information.