Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic modules in F#

In C#, I can compile

static class Foo<T> { /* static members that use T */ }

The result is generic and is not instantiable.

What is the equivalent F# code? module<'a> doesn't compile, and type Foo<'a> is instantiable.

like image 672
Gabriel Avatar asked Jul 31 '09 10:07

Gabriel


People also ask

What are generic modules?

A generic module is indeed an abstraction of a combination by means of giving names to the submodules that will be obtained only at application time. Generic modules are then operations (or functions) on modules.

What is module in F#?

In the context of F#, a module is a grouping of F# code, such as values, types, and function values, in an F# program. Grouping code in modules helps keep related code together and helps avoid name conflicts in your program.


1 Answers

The other answers so far each have part of the picture...

type Foo<'a> private() =          // '
    static member Blah (a:'a) =   // '
        printfn "%A" a

is great. Disregard what Reflector generates, you cannot instantiate this class from within the F# assembly (since the constructor is private), so this works well.

F# does allow static constructors as well, the syntax is to include 'static let' and 'static do' statements in the class (which work analogously to how 'let' and 'do' work as part of the primary constructor body for instances). A full example:

type Foo<'a> private() =             // '
    static let x = 0
    static do printfn "Static constructor: %d" x
    static member Blah (a:'a) =      // '
        printfn "%A" a

//let r = new Foo<int>() // illegal
printfn "Here we go!"
Foo<int>.Blah 42
Foo<string>.Blah "hi"
like image 179
Brian Avatar answered Oct 04 '22 10:10

Brian