F# and Operator Overloads: (>) and (^)

匆匆过客 提交于 2019-12-01 08:25:52

F# has default meanings for these operator symbols that's reasonable for F#. You can always define your own meanings that shadow the defaults, a la

let (>) x y = ...

For example, you could define this operator to mean "T.operator>(U)" (assuming x has type T and y has type U).

See prim-types.fs in FSharp.Core in the source distribution for the default definitions. (They are non-trivial!)

Given the combination of (1) lack of support for a type-class like mechanism on the CLR (for defining common semantics among a set of otherwise-unrelated types) and (2) the fact that primitive types (like 'int') often need to be special-cased for any programming language implementation (e.g. System.Int32 does not define an operator+ method, but most programming languages choose to behave as though such a method exists), it's hard to imagine any generally interoperable operator stuff across all languages on .Net today. There are a lot of design-trade-offs depending on exactly what a language chooses to do (too many interacting issues to sum up here). In any case, you should be able to call any method from F#, and if the default operator behaviors are undesirable, you can redefine (shadow) the operators to the behaviors you want. If there's a particular scenario you have in mind that you're having trouble to make work, let me know.

EDIT

I added more detail at

http://cs.hubfs.net/forums/thread/10869.aspx

I agree, there is inconsistency: operator can be defined, but can't be used.

Are you asking, why F# designers decided to implement comparison with System.IComparable interface rather than operators overload? I don't know why, but in OO language I would prefer IComparable rather than operators overloading. So, I would suggest to F# developers to break C# compatibility and forbid "static member (>) (...)" syntax sugar.

If you are asking how to call these overloaded operators it is pretty easy: use op_Concatenate, op_GreaterThan or op_LessThan static members. (Really, I've got a compiler warning, describing the problem. F# 1.9.6.16)

Runtime Error casting to System.IComparable without any compiler warning definitely is a bug. You can send it to fsbugs@microsoft.com.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!