Search code examples
f#c#-to-f#ilnumerics

Convert C# 'using' keyword to F#


In trying to translate the following C# code to F#, I'm struggling with the 'using' keyword. The following snippet is from the ILNumerics library. How to translate the following?

ILRetArray<double> ObjFuncBFGS2D(ILInArray<double> X) {
    using (ILScope.Enter(X)) {
        return X[0] * X[0] + X[1] * X[1] + 2; 
    }
} 

On a side note, what libraries do F# people tend to use for optimization? I've been using NLoptNet but with very strange convergence issues with routines that converge properly in Matlab and Julia and Python. So either the problem is with my F# translations (granted this is more likely) or the optimization libraries. This is what I'm hoping to pin down. Frankly I'm a bit surprised by the lack of numerical optimization material related to F# on the internet.


Solution

  • The MSDN documentation on resource management in F# is relevant here. To auto-dispose, the usual ways in F# are:

    • use, which replaces let and disposes once the binding goes out of scope
    • using, a function that takes the resource to dispose when finished and a function to execute before disposal, which takes the disposable object as input.

    The code with use might look like this:

    let ObjFuncBFGS2D (X : ILInArray<double>) =
        use myEnteredScope = ILScope.Enter(X)
        X.[0] * X.[0] + X.[1] * X.[1] + 2
    

    Or, with using, like this:

    let ObjFuncBFGS2D (X : ILInArray<double>) =
        using (ILScope.Enter(X)) <| fun _ ->
            X.[0] * X.[0] + X.[1] * X.[1] + 2
    

    I don't use ILNumerics and can't syntax check this, but I hope the idea is clear.