重载度量​​运算符(*) [英] Overloading measure operator (*)

查看:71
本文介绍了重载度量​​运算符(*)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试重载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

请注意,在此示例中,乘积度量正确解析为< 1>,例如在乘以复数的虚数单位时会发生这种情况.没有此重载定义,默认乘积将解析为< i ^ 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

显然,我的重载定义隐藏了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.

这篇关于重载度量​​运算符(*)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆