【问题标题】:F# record constructor functionF#记录构造函数
【发布时间】:2014-08-24 09:42:38
【问题描述】:

有没有办法在 F# 中调用 F# 记录类型的构造函数?

我的动机是我一直在使用 FSharpx 的应用验证,但发现自己编写了许多仅用于构建记录的样板函数。

例如简单样板中的 buildAddress 函数,如果可能的话,我很想摆脱它。

       let buildAddress streetNumber streetLine1 streetLine2 suburb state postcode =
            {
                Address.StreetNumber = streetNumber
                StreetLine1 = streetLine1
                StreetLine2 = streetLine2
                Suburb = suburb
                State = state
                Postcode = postcode
            }

       let validateAddress streetNumber streetLine1 streetLine2 suburb state postcode =
            buildAddress 
                <!> isNumber streetNumber 
                <*> Success streetLine1 
                <*> Success streetLine2 
                <*> Success suburb 
                <*> Success state
                <*> validatePostcode postcode

【问题讨论】:

    标签: f# applicative fsharpx


    【解决方案1】:

    F# 记录实际上是使用构造函数生成的,但似乎无法从 F# 代码中获得。可能 CompilationMapping 属性会处理这个问题,因为构造函数本身没有任何属性。

    您可以做的是使用标准 .NET 反射 (Activator.CreateInstance) 或 FSharp 反射 (FSharpValue.MakeRecord, FSharpValue.PreComputeRecordConstructor 将获得一个可使用的函数) 获取构造函数。然而,他们都希望将参数作为一个装箱对象数组来获取,因此它不能很好地与应用验证相结合。

    我认为您不会得到比现在更清洁的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-25
      • 2013-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-25
      • 2017-06-18
      • 1970-01-01
      相关资源
      最近更新 更多