mutation

One pattern many people follow is to be liberal with mutation when constructing data, but conservative with mutation when consuming data.

let

let permits us to rebind variables.

let age = 52;
age = 53;
age
//=> 53

const

Declaring a variable const does not prevent us from mutating its value, only prevent us from rebinding its name. This is an important distinction.

const ls = []
ls = [1] // not allowed
ls[0] = 1 // allowed

immutable

js没有immutable变量,F#有,它不仅不允许rebinding, 也不允许修改它的值。

js模块跨文件的exprotimport都应该是immutable变量。但它不是,我们假设它是的,从来不会修改它,只是会读取它,执行它。

write-once-only

只能改变一次值的标识符。当值被定义时,变量被设定为undefined,此值用于占位,序不可以读取,这个值只能被写一次,改写的值为非undefined.

用途:

构造List,Array等。
其他必须事先分配内存的场景。

// example 1:
let arr = Array.undefinedCreate 100

// example 2:
let allocListNode head = { head = head; tail = undefined }

let a = allocListNode 1
let b = allocListNode 2
a.tail |> ignore // fail because undefined value is write-only.
a.tail <- b // ok! write it to a defined value.
a.tail |> ignore // ok! now, it is a defined value, which is a normal immutable value.
a.tail <- a.tail // fail because now, it is a defined value, which is a normal immutable value.
let c = allocListNode 3
b.tail <- c