Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extension methods for specific generic types

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.

like image 790
Noldorin Avatar asked Oct 07 '09 13:10

Noldorin


2 Answers

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

like image 60
kvb Avatar answered Sep 28 '22 12:09

kvb


Generic extension methods are now available in F# 3.1:

open System.Runtime.CompilerServices
open System.Collections.Generic

[<Extension>]
type Utils () =
    [<Extension>]
    static member inline Abc(obj: IEnumerable<int>) = obj.ToString()

printfn "%A" ([1..10].Abc())
like image 45
dharmatech Avatar answered Sep 28 '22 11:09

dharmatech