在第三章,你第一次接触了记录类型,我并没有讨论如何更新它们的字段。这是因为,默认情况下记录类型是不可更改的。F#提供了特殊的语法,以允许更新记录类型里的字段,在记录类型的字段前面使用关键字mutable。我必须强调,这一操作改变的内容是记录的字段,而非记录本身。
#light
type Couple = { her : string ; mutable him : string }
let theCouple = { her = "Elizabeth Taylor " ; him = "Nicky Hilton" }
let print o = printf "%A\r\n" o
let changeCouple() =
print theCouple;
theCouple.him <- "Michael Wilding";
print theCouple;
theCouple.him <- "Michael Todd";
print theCouple;
theCouple.him <- "Eddie Fisher";
print theCouple;、
theCouple.him <- "Richard Burton";
print theCouple;
theCouple.him <- "Richard Burton";
print theCouple;
theCouple.him <- "John Warner";
print theCouple;
theCouple.him <- "Larry Fortensky";
print theCouple
changeCouple()
执行结果:
{her = "Elizabeth Taylor "; him = "Nicky Hilton"}
{her = "Elizabeth Taylor "; him = "Michael Wilding"}
{her = "Elizabeth Taylor "; him = "Michael Todd"}
{her = "Elizabeth Taylor "; him = "Eddie Fisher"}
{her = "Elizabeth Taylor "; him = "Richard Burton"}
{her = "Elizabeth Taylor "; him = "Richard Burton"}
{her = "Elizabeth Taylor "; him = "John Warner"}
{her = "Elizabeth Taylor "; him = "Larry Fortensky"}
这个例子显示一个mutable记录的动作。一个类型,couple,定义其字段him是一个mutable但字段her不是。接下来,实例化一个couple,然后改变him的值多次,每次都输出结果。请注意,mutable关键字并没有应用于每个字段,因此,任何尝试更新一个非mutable的字段的动作都会导致一个编译错误,如下所示。
#light
theCouple.her <- "Sybil Williams";
print_any theCouple
如果你编译这段代码,你将得到以下错误消息:
prog.fs(2,4): error: FS0005: This field is not mutable