8.2.3.1 mutable state using reference cells
To answer this question, we need to be able to create some states to capture. One method is to use let mutable, however, this does not work because the mutable value can only be used locally and cannot be caught by a closure.
The second method is to use a reference (REF) type to create a mutable value, the abbreviation for a reference cell (reference cell), which is a small object that can contain mutable values (in fact, a record type declared as F #). To understand the principle of reference types, we define the same type in C #, as you can see, quite simply:
Class Ref<t> {
Public Ref (T value) {value = value;}
Public T Value {get; set;}
}
The most important thing here is that the Value property is mutable, so when we create a variable of the immutable ref<int> type, we can still change the value it represents. Listing 8.8 is an example of using a reference cell in F #, showing the equivalent of C # using the ref<t> type code; in F #, the type is not directly accessed because there is a function, also called ref, that creates the reference unit, and two operators that set and read the value.
Listing 8.8 Using reference cells in F # and C #
F # Interactive |
C# |
Let St = ref 10 ST: = 11 Printfn "%d" (!st) |
var st = new Ref<int> (10); St. Value = 11; Console.WriteLine (St. Value); |
In the first line, we create a reference unit that contains integers, just like the ref<t> type declared in C #, where F # 's Ref type is generic, so we can use it to hold any type of value; The next two lines demonstrate the operator using the Reference Unit: Assignment (: = ) and dereference (! , F # operators correspond to setting and reading property values, but the syntax is more convenient.
[
In F # 4.0, the use of mutable values is simplified.
In F #, although the value is immutable by default, mutable values are also allowed. In the past, the keyword mutable was used to illustrate mutable values using the stack, which was modified using the <-operator, and if the variable value was captured by a closure, then the value would use the heap, which would require the use of the ref syntax, and the increasing value was through the: = operator.
These grammatical differences make the code less elegant and confusing to developers, making it difficult to figure out which method to use.
Now, with F # 4.0, developers can mutable all mutable values with a single keyword, and the rest of the work is done by the compiler: if possible, create a change on the stack, or implicitly convert to a reference cell.
For the wealthy advanced user who knows stacks and stacks very well, the ability to enable warning 3180 (in Fsc.exe or fsi.exe, using--warnon:3180) is notified when the mutable declaration is implicitly converted to ref.
]
8.2.3.1 mutable state using reference cells