views:

186

answers:

2

I'm attempting to create various extension method for a generic type bound to specific generic type parameters in F#, but the language does not seem to be allowing me:

What I want to do is something like the following:

type IEnumerable<int> with
    member this.foo =
        this.ToString()

Yet it gives me the compiler error (underlining the int keyword):

Unexpected identifier in type name. Expected infix operator, quote symbol or other token.

The following does work, though it does not specifically bind the generic type parameter to int, as I want:

type IEnumerable<'a> with
    member this.foo =
        this.ToString()

Is there any way to accomplish this aim in F# - am I perhaps just using the wrong syntax? If not, I would appreciate if someone could suggest a workaround, perhaps using type constraints somewhere.

A: 

Well, you can use constraints - but not with sealed types like int.

type IEnumerable<'a when 'a :> InheritableType> =
member this.Blah =
    this.ToString()

Hmm...

Massif
Thanks for the suggestion, but indeed, I'm working with a sealed type here, so it doesn't quite work.
Noldorin
This probably doesn't do quite what you think... You're actually defining a new `IEnumerable` type - try calling the extension on an existing `IEnumerable<InheritableType>`.
kvb
+4  A: 

This isn't possible in the current version of F#, unfortunately. See related question here.

kvb
Seems you are indeed correct. Thanks anyway.
Noldorin
This feature is tracked by a suggestion in the internal F# bug database "4548: Support extension methods for specific type instantiations" but it is unlikely to be make the cut for the VS2010 release.
Brian