【问题标题】:F# creating generic function with generic units of measureF#使用通用度量单位创建通用函数
【发布时间】:2018-06-15 14:35:33
【问题描述】:

我觉得我可能在与 F# 想思考类型和度量单位的方式作斗争,但我想问这个问题,以防我遗漏了一些明显的东西。我使用类型和度量单位来确保所有操作都具有类型对齐。我想定义一个通用的tryDivide 函数,它将采用匹配的类型,但我在圈子里跑来跑去试图让它工作这是工作的非泛型版本:

[<Measure>] type USD (* US Dollars *)

let tryDivide a b =
    match b > 0M with
    | true -> a / b |> decimal |> Some
    | false -> None


type Cost = decimal<USD>

module Cost =
    let create v : Cost =
        v * 1M<USD>

    let tryDivide (a:Cost) (b:Cost) =
        tryDivide (decimal a) (decimal b)

let costA = Cost.create 10M
let costB = Cost.create 20M

let ratio = Cost.tryDivide costA costB

问题是我必须为每种类型定义一个tryDivide 函数(例如:Cost.tryDivide)。有什么方法可以使顶级tryDivide 函数对类型和度量单位通用?理想情况下,它会采用任何类型,它实际上只是一个decimal&lt;'u&gt;,它具有度量单位。我尝试了各种函数签名,但没有任何效果。如果我执行以下操作,则会将输入限制为 int

let tryDivide (a: 'u) (b: 'u) =
    let x = (decimal a)
    let y = (decimal b)
    match y > 0M with
    | true -> x / y |> decimal |> Some
    | false -> None

如果我的思维过程根本上是错误的,我很想听听。我为每种类型手动编码一个tryDivide,这似乎效率低下。

【问题讨论】:

    标签: generics f# units-of-measurement


    【解决方案1】:

    我马上就找到了答案。您需要在单位上设置 b &gt; 0M 通用。为此,您需要打开Microsoft.FSharp.Core.LanguagePrimitives 模块并使用DecimalWithMeasure 函数。这是tryDivide函数的新版本:

    let tryDivide a b =
        match b > (DecimalWithMeasure 0M) with
        | true -> a / b |> Some
        | false -> None
    

    【讨论】:

      猜你喜欢
      • 2010-10-02
      • 2010-10-04
      • 1970-01-01
      • 2015-05-01
      • 2014-12-19
      • 2021-12-15
      • 2016-04-06
      • 2014-10-08
      • 1970-01-01
      相关资源
      最近更新 更多