linkerro
linkerro

Reputation: 5458

How do you write a generic F# delegate declaration?

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?

Upvotes: 5

Views: 455

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243051

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>

Upvotes: 8

Related Questions