1
2
3
4
5
6
type Foo = 
  class
    static member counter : int = 0
    val mycount : int
    new () as this { mycount = (let v = counter in (counter <- v+1; v)) }
end

How about:

1
2
3
let count =
   let n = ref 0 in
   fun () -> incr n; !n

Cheers,

Jon.

By on 10/23/2006 7:56 AM ()

As far as I know, it is currently not possible to declare static field in F#. My workaround for this is to create module with the value (which behaves just like static field) and to add static getter/setter to the class:

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

module Foo_static = begin
  let counter = ref 1;
end;;

type Foo = class 
  new() = { }
  member this.counter
    with get() = !Foo_static.counter;
    and set(value) = Foo_static.counter := value; 
end;;

By on 10/13/2006 5:42 AM ()

F# pretty-printing in comments. Neat.

Yes, this is what I was going to do as a fall-back, but it felt better from an OO perspective to try to make it part of the class. I guess I'll worry about elegance later [:)]

It was at least my interpretation that static fields were possible, as the compiler didn't complain about my use of

1
 static member counter : int = 0

, unless this doesn't do what I thought it did. I suppose it could actually mean that counter is a static property with default get/set methods supplied.

Strangely enough, today Firefox isn't choking on the "composition" page's JavaScript. There really needs to be some exhaustive way to test implementations for "compliance".

By on 10/13/2006 6:28 AM ()

Hi,
I didn't realize it for the first time, but the

1
static member counter : int = 0

is compiled by the F# as a static method that returns 0, so unfortunately you'll have to use some "hack" for now. However I think that statics fields should be implemented in F# sooner or later.

By on 10/13/2006 12:09 PM ()

Hi guys,

Yep, Tomas' solution is the correct one for now. I agree we should support mutable static fields in classes.

Don

By on 10/14/2006 9:26 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