Calling a F # function that has a function parameter from C #

In F #, I have a function:

module ModuleName let X (y: int -> unit) = () 

How can I call it in C #? Ideally, it would look like

 ModuleName.X(x => x*x); 

But this lambda syntax does not implicitly convert to FSharpFunc.

+4
source share
2 answers

The easiest approach is to expose your API using standard .NET delegate types. In this case, this means that your F # definition should look larger:

 let X (y:Action<int>) = () 

However, if you want your F # API to be the same as it is now, you can use FuncConvert.ToFSharpFunc from C #

 ModuleName.X(FuncConvert.ToFSharpFunc(x => x*x)); 
+12
source

You must do this using the static FSharpFunc.FromConverter method: http://msdn.microsoft.com/en-us/library/ee353520.aspx

 ModuleName.X(FSharpFunc.FromConverter(x => x*x)); 

EDIT: I just noticed that your function calls int -> unit , but your call points to int -> int . To create an FSharpFunc that returns one, you can use one of the static methods of the static FuncConvert class.

+2
source

Source: https://habr.com/ru/post/1403989/


All Articles