Call a higher order F# function from C#

偶尔善良 提交于 2019-12-20 09:37:37

问题


Given the F# higher order function (taking a function in parameter):

let ApplyOn2 (f:int->int) = f(2)  

and the C# function

public static int Increment(int a) { return a++; } 

How do I call ApplyOn2 with Increment as parameter (from C#)? Note that ApplyOn2 is exported as Microsoft.FSharp.Core.FSharpFunc<int,int> which do not match with Increment's signature.


回答1:


If you would like to provide a more friendly interop experience, consider using the System.Func delegate type directly in F#:

let ApplyOn2 (f : System.Func<int, int>) = f.Invoke(2)

You would be able to call your F# function very easily in C# like this:

MyFSharpModule.ApplyOn2(Increment); // 3

There is an issue with the Increment function as you have written it, however. You need the prefix form of the increment operator in order for your function to return the correct result:

public static int Increment(int a) { return ++a; }



回答2:


To get an FSharpFunc from the equivalent C# function use:

Func<int,int> cs_func = (i) => ++i;
var fsharp_func = Microsoft.FSharp.Core.FSharpFunc<int,int>.FromConverter(
    new Converter<int,int>(cs_func));

To get a C# function from the equivalent FSharpFunc, use

var cs_func = Microsoft.FSharp.Core.FSharpFunc<int,int>.ToConverter(fsharp_func);
int i = cs_func(2);

So, this particular case, your code might look like:

Func<int, int> cs_func = (int i) => ++i;
int result = ApplyOn22(Microsoft.FSharp.Core.FSharpFunc<int, int>.FromConverter(
            new Converter<int, int>(cs_func)));



回答3:


Just create reference to your assembly:

#r @"Path\To\Your\Library.dll"
let ApplyOn2 (f:int->int) = f(2)
ApplyOn2 Library.Class.Increment


来源:https://stackoverflow.com/questions/1952114/call-a-higher-order-f-function-from-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!