在进行作业时是否可以在F#中强制记录类型?

时间:2013-12-07 11:44:53

标签: f#

要解释我认为最好用一个例子:

type myRec = {x: string}
type myRec2 = {x: string}
let x = {x = "hello"}
let y(a: myRec) = a.x
y(x);;

  y(x);;
   --^

error FS0001: This expression was expected to have type
    myRec    
but here has type
    myRec2

那么,如果xmyRec具有相同的签名,我如何强制myRec拥有myRec2类型?

2 个答案:

答案 0 :(得分:11)

let x = { myRec.x = "hello" }
// or
let x:myRec = { x = "hello" }
// or
let x = { x = "hello" } : myRec

the documentation中提供了更多详细信息和示例。

编辑:注释中的备选方案。

答案 1 :(得分:2)

是的,你可以:

let x = { new myRec() with x = "hello" }

使用and分配更多字段:

let x = { new myRec3() with x = "hello" and y = "bye" }