Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accepting FSharpFunc where Func is expected

As mentioned in this question, methods expecting a Func will not accept an F# function value.

What's a good approach to overloading a method such that it will accept F# function values?

like image 410
dharmatech Avatar asked Dec 12 '22 06:12

dharmatech


2 Answers

I know this is not what you're asking, but instead of directly attempting to support F# from code written in C# (as I get the impression that you're trying to do), it would be more idiomatic to provide a small adapter module to make functional composition easier from F#.

There are many examples of this, such as FSharp.Reactive, which provides functions to make it easier to use Reactive Extensions from F#.

For example, if you want to access Enumerable.All from F#, you could write a little adapter function, e.g.

let all f (s : 'a seq) = s.All (fun x -> f x)

which you could then use like this:-

seqA |> all abc

However, in the case of All, you can use the built-in F# functions for that:

seqA |> Seq.forall abc
like image 113
Mark Seemann Avatar answered Dec 20 '22 02:12

Mark Seemann


Wouldn't just creating a Func<,> be enough?

let doSomethingWithFunc (f : System.Func<_,_>) =
    42

let doSomethingWithFSharpFunc (f : 'a -> 'b) =
    System.Func<_,_>(f) |> doSomethingWithFunc

(fun x -> 42) |> doSomethingWithFSharpFunc
like image 24
Klark Avatar answered Dec 20 '22 01:12

Klark