F#基础教程 定义mutable记录类型

     在第三章,你第一次接触了记录类型,我并没有讨论如何更新它们的字段。这是因为,默认情况下记录类型是不可更改的。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

转载于:https://www.cnblogs.com/IBBC/archive/2011/12/08/2280577.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值