【问题标题】:Is it possible to force record type in F# when doing an assignment?进行分配时是否可以在 F# 中强制记录类型?
【发布时间】:2015-02-11 21:20:34
【问题描述】:

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

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

如果myRecmyRec2 具有相同的签名,我如何强制x 具有myRec 类型?

【问题讨论】:

    标签: f#


    【解决方案1】:
    let x = { myRec.x = "hello" }
    // or
    let x:myRec = { x = "hello" }
    // or
    let x = { x = "hello" } : myRec
    

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

    编辑:合并了 cmets 的替代品。

    【讨论】:

    • 我还发现我可以写:let x:myRec = {x = "hello"},我认为这是最可读的。
    • 为了完整起见,我添加let x = { x = "hello" } : myRec
    • @JohnReynolds,在这里几乎得到了一点 perl 的古老口头禅:“有不止一种方法可以做到这一点。”好不好我说还为时过早。
    • @TomasJansson :一如既往,一致性是关键。 :-]
    【解决方案2】:

    是的,你可以:

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

    使用and 分配更多字段:

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

    【讨论】:

    • 这会导致额外的(不必要的)分配。
    猜你喜欢
    • 1970-01-01
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2023-03-03
    • 2020-02-12
    • 2016-11-21
    • 1970-01-01
    相关资源
    最近更新 更多