Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you write a generic F# delegate declaration?

Tags:

f#

c#-to-f#

So, how do you write a generic delegate declaration in f#?

I want to get the equivalent of this c# declaration:

public delegate Result<TOutput> Parser<TInput, TValue>(TInput input);

I haven't been able to find documentation on how this might be achieved, even though it's a quite common to have to write generic delegates.

Any ideas or pointers?

like image 661
linkerro Avatar asked Jan 19 '16 00:01

linkerro


1 Answers

You can define a generic delegate as follows:

type Parser<'TInput, 'TOutput> = delegate of 'TInput -> Result<'TOutput>

In F#, the generic parameters are written with a single quote at the beginning (to distinguish them from normal types), so that's why you need'TInput.

Just for the record, I don't think I ever needed to define a delegate in F#. I guess they are still useful for C# interop, but even then, I would probably just define a type alias for a Func delegate, or (when you are not going to be calling this from C#, just an ordinary F# function):

// Alias for a standard .NET delegate
type Parser<'TInput, 'TOutput> = System.Func<'TInput, Result<'TOutput>>

// Alias for a normal F# function
type Parser<'TInput, 'TOutput> = 'TInput -> Result<'TOutput>
like image 172
Tomas Petricek Avatar answered Sep 23 '22 16:09

Tomas Petricek