F# 中的重载内联运算符:( |+| ) [英] Overloaded inline operators in F#: ( |+| )

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

问题描述

我正在尝试定义一个重载运算符,例如|+|,如下所示:

I'm trying to define an overloaded operator, e.g. |+|, as the following:

let inline ( |+| ) (m1 : #IMeasurable) (m2 : #IMeasurable) = m1.Measure + m2.Measure

问题是,我不能做这样的事情:

The problem is, I can't do something like:

let three = m1 |+| m2 |+| m3

因为运算符 |+| 未针对 (m1 : int) (m2 : #IMeasurable) 情况定义.有没有办法重载这个运算符或使用静态类型约束来使上述表达式成为可能?有没有办法修改 IMeasurable (我可以编辑)以便这是可能的?还有什么可以让上述表达式起作用的吗?

Because the operator |+| isn't defined for the case (m1 : int) (m2 : #IMeasurable). Is there a way to overload this operator or use static type constraints to make the above expression possible? Is there a way to modify IMeasurable (which I can edit) so that this is possible? Anything else that would allow the above expression to work?

谢谢.

推荐答案

type Overloads = Overloads with
    static member ($) (Overloads, m1: #IMeasurable) = fun (m2: #IMeasurable) -> m1.Measure + m2.Measure 
    static member ($) (Overloads, m1: int) = fun (m2: #IMeasurable) -> m1 + m2.Measure

let inline ( |+| ) m1 m2 = (Overloads $ m1) m2

未经过测试,因为我没有 IMeasurable,但它可以胜任.

Not tested, since I don't have IMeasurable, but it may do the job.

这篇关于F# 中的重载内联运算符:( |+| )的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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