问题描述
我在尝试为 Measure 类型重载 (*) 运算符时卡住了.
I am stuck attempting to overload the (*) operator for a Measure type.
我想看到的是:
> let x = 1.0<i> * 1.0<i>;;
val x : float = -1.0
以下定义似乎可以解决问题:
The following definition appears to do the trick :
> let inline (*) (v1 : float<i>) (v2 : float<i>) = float(-1) * float(v1) * float(v2);;
val inline ( * ) : float<i> -> float<i> -> float
请注意,此示例中的乘积度量正确解析为 ,例如在乘以复数的虚数单位时会发生这种情况.如果没有这个重载定义,默认乘积解析为 <我^2>.
Note that the product measure in this example correctly resolves to <1> as which happens for example when multiplying the imaginary unit of a complex number. Without this overloading definition the default product resolves to < i^2>.
但是上面的重载定义有一个令人讨厌的副作用:
But the overloading definition above has the nasty side effect that :
> let y = 1.0 * 1.0;;
let y = 1.0 * 1.0;;
--------^^^
stdin(11,9): error FS0001: This expression was expected to have type
float<i>
but here has type
float
显然,我的重载定义隐藏了浮点类型的 (*) 运算符.
Apparently my overloading definition hides the (*) operator for the float type.
我做错了什么?
推荐答案
请注意,您正在重新定义 (*)
运算符,而不是重载它.
Note that you are redefining the (*)
operator rather than overloading it.
让它工作的诀窍是使用中间类型编写一些东西,如下所示:
The trick to get it working is to write something using an intermediate type, like this:
type Mult = Mult with
static member ($) (Mult, v1: float<i>) = fun (v2: float<i>) ->
float(-1) * float(v1) * float(v2)
static member inline ($) (Mult, v1 ) = fun v2 -> v1 * v2
static member ($) (Mult, v1: Mult) = fun () -> Mult //Dummy overload
let inline (*) v1 v2 = (Mult $ v1) v2
顺便说一句,使用度量单位的有趣方式.
BTW funny way to use units of measure.
这篇关于重载度量运算符 (*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!