Hi,
as far as I know, F# doesn't have static constructors. If you need to initialize some global values, you can use modules. Here is an examle that uses module to generate a new unique index for a class when it is created:

1
2
3
4
5
6
7
8
9
10
11
12
 
module Globals = 
  let private count = ref 0 // global code (1)
  do printf "initializing..." // global code 
  let GetCount() = 
    let v = !count
    count := v + 1
    v
    
type Test() = 
  let index = Globals.GetCount()
  member x.Index = index

This way, you can probably do anything that you can write using static constructors. However, there is an important difference. Static constructor is invoked first time you create any instance of the class where it is contained. On the other side, global code in a module, such as (1) is executed immediately when the program starts.

T.

By on 10/11/2008 2:42 PM ()

Hi I am trying to emulate ML style functors by passing in a record of functions meeting a signature. For instance I have a table that takes as a functorial type parameter a set of functions called MaxKey MinKey MaxKeyValue and MinKeyValue. These functions are static over the type but currently have to be passed in as a constructor parameter to each instance. If I could make this a static property of the type would it be possible to do something like

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 

type SymbTab = Table<string, variable>(KeyOps<string> ops)

with    

   static member Empty(ops) = new Table<string, variable>(ops)

   member x.KeyOps with get() ops   // for some reason this does not work as a static member

   ...   more member declarations

 

here set the static property

or possible when I declare the generic type parameters have the

KeyOps type automatically generated

I hope this is clear what I am trying to do.

David

By on 10/11/2008 5:49 PM ()

thanks that is exactly what I was looking for

By on 10/11/2008 5:51 PM ()

Actually, I was wrong :-) F# now supports static constructors too (thanks to Brian for letting me know)!
An example would look like this:

1
2
3
4
5
 
type Foo() =
    static let x = 0 // static value
    static do printfn "hi" // code in the static constructor
    // (...)

So the code that I wrote in the earlier example would look like this:

1
2
3
4
5
6
7
 
type Foo() =
    static let mutable count = 0
    static do printfn "initializing..."
    let index = count
    do count <- count + 1
    member x.Index = index

This means that F# actually gives you two different ways. When using static constructors, you'll get the same behavior as in C#, while when using modules, the code will be executed when the program starts.

By on 10/11/2008 5:42 PM ()
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