Home > Back-end >  C# - F# interoperability, how to get result instead of FSharpFunc
C# - F# interoperability, how to get result instead of FSharpFunc

Time:11-06

I'm learning F# and would like to write simple F# library which can be consumed from C# application. It works as expected for trivial F# functions e.g.

let Square x = x * x

From C# I can consume it and get the expected value:

var sqaredNumber = MyFSharpLibrary.Square(5);

However when I use a Sequence / IEnumerable<T> as function parameter I got FSharpFunc object instead of the result. Here is my function:

let FilterEvenNumbers input = Seq.filter(fun x -> x % 2 = 0)

And this is how I try to use it from C# code:

 var numbers = new int[] { 1, 2, 3, 4 };
 var filteredNumbers = MyFSharpLibrary.FilterEvenNumbers(numbers);

Instead of value filteredNumbers contains FSharpFunc object. I could use method Invoke on that object but would like to avoid extra complexity. How can I achieve that ?

CodePudding user response:

This is because your function declaration returns a function. If you enter it into dotnet fsi you'll see the signature:

val FilterEvenNumbers: input: 'a -> (seq<int> -> seq<int>)

See the parentheses? That means a single FSharpFunc object is returned, and it is the function that you call with input.

As you can see, input isn't passed to the filtering function, nor is its type associated at all with the inferred parameterized types for Seq.

To fix this, you need to pass input to Seq.filter.

  • Related