gpt4 book ai didi

types - 如何直接在 Measure 类型本身上通过静态成员 New 生成 bool 成员类型?

转载 作者:行者123 更新时间:2023-12-04 20:03:30 27 4
gpt4 key购买 nike

我如何在 F# 中创建一个 Measure Type,它有一个静态成员 New,可以给它一个值并为 bool 生成给定的 Measure Type?

我有这个用于 int、int64 和 decimal,效果很好。

    [<Measure>] type MyInt = static member New value = value * 1<MyInt>
[<Measure>] type MyInt64 = static member New value = value * 1L<MyInt64>
[<Measure>] type MyDecimal = static member New value = value * 1m<MyDecimal>

但这行不通:

    [<Measure>] type MyBool = static member New value = value * true<MyBool>

编译错误是Unexpected token '>' or incomplete expression

我也用字符串和 DateTime 遇到过这个问题。我的目标是基本上使用 Measure 类型来提供编译时检查,而不会影响单案例联合类型包装器的运行时性能。 ( See this answer by Jack P. for reference. )

理想情况下,我很乐意将这个概念用于我的所有类型,但我没有看到非数字类型如何。

最佳答案

因此,只有某些内置类型具有内置度量类型定义

从规范来看,这些是

type float<[<Measure>] 'U>
type float32<[<Measure>] 'U>
type decimal<[<Measure>] 'U>
type int<[<Measure>] 'U>
type sbyte<[<Measure>] 'U>
type int16<[<Measure>] 'U>
type int64<[<Measure>] 'U>

对于其他类型,您可以定义自己的类型。

对于数字类型,您可以使用 LanguagePrimitives.Int32WithMeasure 等编写您的 new 函数,这实际上对于 float 来说稍微快一些。我认为最近对其他数字类型进行了优化,以便在编译时完成乘以 1。

关于types - 如何直接在 Measure 类型本身上通过静态成员 New 生成 bool 成员类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38013698/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com