You can do this, but you have to use F# library features. Take a look at prim-types.fs (C:\Program Files\FSharp-1.9.6.2\source\fsharp\FSharp.Core). You can define inline functions, then special case for specific types.

This will generate a warning, but it still works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
let inline GenericZero< ^a when ^a : (static member Zero : ^a) > : ^a =
    GenericZeroDynamic<(^a)>()
    when ^a : int32       = 0
    when ^a : float       = 0.0
    when ^a : float32     = 0.0f
    when ^a : int64       = 0L
    when ^a : uint64      = 0UL
    when ^a : uint32      = 0ul
    when ^a : nativeint   = 0n
    when ^a : unativeint  = 0un
    when ^a : int16       = 0s
    when ^a : uint16      = 0us
    when ^a : sbyte       = 0y
    when ^a : byte        = 0uy
    when ^a : decimal     = 0M
     // According to the somewhat subtle rules of static optimizations,
     // this condition is used whenever ^a is resolved to a nominal type
    when ^a : ^a = (^a : (static member Zero : ^a) ())
By on 4/17/2009 1:56 PM ()

Oh but yes, as Kurt says, you won't be able to have the constraints to statically check it. There might be a a way to make the default case generate a compile time warning -- maybe by calling an ObsoleteAttributed function?

By on 4/17/2009 2:04 PM ()

This is a known limitation in the static member contraints that you're using: they don't "see" type extensions to types defined in other modules.

By on 4/17/2009 8:01 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper