为什么主流的静态类型语言不支持按返回类型重载函数/方法?我想不出有什么能做到。这似乎并不比支持按参数类型重载更有用或更合理。为什么它不那么受欢迎呢?
当前回答
如果你稍微换个角度来看,这个重载特性并不难管理。考虑以下几点:
public Integer | String f(int choice){
if(choice==1){
return new string();
}else{
return new Integer();
}}
如果一种语言确实返回重载,它将允许参数重载,但不允许重复。 这将解决以下问题:
main (){
f(x)
}
因为只有一个f(int)选项可供选择。
其他回答
在haskell中,这是可能的,即使它没有函数重载。Haskell使用类型类。在程序中你可以看到:
class Example a where
example :: Integer -> a
instance Example Integer where -- example is now implemented for Integer
example :: Integer -> Integer
example i = i * 10
函数重载本身并不流行。我所见过的大多数使用它的语言是c++,也许是java和/或c#。在所有动态语言中,它是:
define example:i
↑i type route:
Integer = [↑i & 0xff]
String = [↑i upper]
def example(i):
if isinstance(i, int):
return i & 0xff
elif isinstance(i, str):
return i.upper()
因此没有什么意义。大多数人不感兴趣的是语言是否能帮助你在使用它的时候省去一行字。
模式匹配有点类似于函数重载,我想有时工作方式也类似。但它并不常见,因为它只对少数程序有用,而且在大多数语言上实现起来很棘手。
你可以看到,在语言中还有无限多更好更容易实现的特性,包括:
动态类型 内部支持列表,字典和unicode字符串 优化(JIT、类型推断、编译) 集成部署工具 库支持 社区支持和聚集场所 丰富的标准库 好的语法 读取eval打印循环 对反射编程的支持
大多数静态语言现在也支持泛型,这将解决您的问题。如前所述,如果没有参数差异,就无法知道调用哪一个。如果你想这样做,使用泛型就可以了。
根据返回元素是标量还是数组,Octave允许不同的结果。
x = min ([1, 3, 0, 2, 0])
⇒ x = 0
[x, ix] = min ([1, 3, 0, 2, 0])
⇒ x = 0
ix = 3 (item index)
Cf也是奇异值分解。
从另一个非常相似的问题(dupe?)中窃取一个c++特定的答案:
函数返回类型不会在重载解析中发挥作用,因为Stroustrup(我假设来自其他c++架构师的输入)希望重载解析是“上下文独立的”。参见“c++编程语言,第三版”中的“重载和返回类型”。
原因是为了保持独立于上下文的单个操作符或函数调用的解析。
They wanted it to be based only on how the overload was called - not how the result was used (if it was used at all). Indeed, many functions are called without using the result or the result would be used as part of a larger expression. One factor that I'm sure came into play when they decided this was that if the return type was part of the resolution there would be many calls to overloaded functions that would need to be resolved with complex rules or would have to have the compiler throw an error that the call was ambiguous.
而且,上帝知道,c++的重载解析已经足够复杂了……
在这样一种语言中,你将如何解决以下问题:
f(g(x))
如果f有重载void f(int)和void f(字符串)和g有重载int g(int)和字符串g(int)?你需要某种消歧器。
我认为,在需要这个函数的情况下,最好为函数选择一个新名称。