Does anyone know how to define a static mutable variable in a module. For example, i have a module file named MyModule1.fs

As far as I know, you cannot use a mutable variable unless it is both defined and used within the same function or lambda body. However, you can use a ref reference, which is similar in some respects to a pointer (in fact, it is implemented as a structure with a mutable value).

let myString = ref "initial value"
let myFunction() = myString := "new value"
let myUseString() = printfn "%s" !myString

If you insist on working with uninitialized variables, you can use a reference to a string option and test for an empty value, as in:let myString' = ref None
let myFunction'() = myString' := Some("new value")
let myUseString'() = match !myString' with
| Some(s) -> printfn "%s" s
| None -> failwith "uninitialized"

By on 3/26/2009 7:16 AM ()

Modules are static. So no extra work needed:

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

> module Test =
-   let mutable count = 0
-   let next() = count <- count + 1; count
- ;;

module Test = begin
  val mutable count : int
  val next : unit -> int
end

> Test.next();;
val it : int = 1
> Test.next();;
val it : int = 2

As jhugard mentions, there are restrictions on mutables. Notably, you can't use a local mutable in a lambda.

By on 3/26/2009 9:20 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