F#运算符重载奇怪的行为 [英] F# operator overloading strange behavoir

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

问题描述

假设出于某种奇怪的原因,我想拥有此功能:

Let's say that for some strange reason I want to have this function:

let (~-) (str:string) = 42

所以我可以做这样的事情,结果是42:

So I can do something like this and get 42 as result:

-"test"
val it : int = 42

哪个很好.但是现在当我这样做时:

Which is fine. But now when I do:

let a = 100
-a

我得到:

error FS0001: This expression was expected to have type
    string    
but here has type
    int    

知道为什么会这样吗?

推荐答案

使用let定义运算符时,新定义将隐藏所有先前的运算符定义.因此,在您的示例中,您将隐藏一元减号(适用于数字)的默认实现,并将其替换为仅对字符串有效的新运算符.

When you define operators using let, the new definition hides all previous definition of the operator. So in your example, you are hiding the default implementation of the unary minus (which works for numbers) and replacing it with a new operator that only works on strings.

在内置类型上重新定义重载运算符并不容易.如果需要,最好避免使用运算符(仅使用函数).但是,如果要为自定义类型提供重载的运算符,则可以通过将运算符添加为静态成员来实现:

It is not easy to re-define overloaded operators on built-in types. If you need that, it is probably better idea to avoid using operators (just use a function). However, if you want to provide an overloaded operator for a custom type, you can do this by adding operator as a static member:

type MinusString(s:string) =
  member x.Value = s
  /// Provide unary minus for MinusString values
  static member (~-) (ms:MinusString) =
    MinusString("-" + ms.Value)

-(MinusString "hi") // Returns "-hi"

如果您真的想重新定义像一元减号这样的内置运算符并使它在string上运行,那么实际上有一种方法可以使用

If you really want to redefine built-in operator like unary minus and make it work on string, then there is actually a way to do this using a trick described in earlier SO answers. However, I would only use this if you have a good reason.

这篇关于F#运算符重载奇怪的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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