Search code examples
f#type-extension

Extension method with F# function type


The MSDN doc on Type Extensions states that "Before F# 3.1, the F# compiler didn't support the use of C#-style extension methods with a generic type variable, array type, tuple type, or an F# function type as the “this” parameter." (http://msdn.microsoft.com/en-us/library/dd233211.aspx) How can be a Type Extension used on F# function type? In what situations would such a feature be useful?


Solution

  • Here is how you can do it:

    [<Extension>]
    type FunctionExtension() =
        [<Extension>]
        static member inline Twice(f: 'a -> 'a, x: 'a) = f (f x)
    
    // Example use
    let increment x = x + 1
    let y = increment.Twice 5  // val y : int = 7
    

    Now for "In what situations would such a feature be useful?", I honestly don't know and I think it's probably a bad idea to ever do this. Calling methods on a function feels way too JavaScript-ey, not idiomatic at all in F#.