5

I need to implement a static extension method supporting member constraints on some basic primitive types like integers, floats, etc. Here's my code for signed integers:

module MyOperators =
    let inline foo (x : ^T) = (^T : (static member Foo : ^T -> int) (x)) 

    type System.Int32 with 
        static member Foo(x : Int32) = 7 // static extension

Test code:

open MyOperators    
let x = foo 5 // x should be 7

But compiler complains with error:

The type 'System.Int32' does not support any operators named 'Foo'

What am I missing here? Thanks!

elmattic
  • 12,046
  • 5
  • 43
  • 79
  • If I'm understanding you correctly, I would think that even if you can do this, it's not an especially good idea. Tinkering with basic language mechanisms has always struck me as an anti-pattern. Think of the fact that someone besides you may have to work on this code at some point in the future. You may even have to maintain this code yourself at some point in the future when you've not worked on it for a while. Modifications to intrinsic types can lead to several "WTF?" moments. – Onorio Catenacci Sep 10 '10 at 12:35

2 Answers2

5

Static member constraints in F# never find 'extension methods', they can only see intrinsic methods on types (and a few special cases called out in the F# language spec).

Perhaps you can use method overloading instead? What is your ultimate goal?

Brian
  • 117,631
  • 17
  • 236
  • 300
  • Thanks. Ultimate goal was to add my own set of intrinsics to FSharp.Core.Operators, such as trigonometrical functions, etc. – elmattic Sep 09 '10 at 23:15
3

F#'s static type constraints don't work with extension methods. Extension methods cannot statically be checked at compile time, and even so, you can have multiple definitions for Int32::Foo (depending on which namespace you imported).

Unfortunately, to solve your problem you might have to resort to using reflection.

Chris Smith
  • 18,244
  • 13
  • 59
  • 81
  • 6
    I don't think this is technically infeasible - extension methods are checked statically at compile time (when you call them), so they could be also accepted by member constraints. It makes sense that this is not supported, but it should be possible... – Tomas Petricek Sep 10 '10 at 00:11