当存在重载函数时,Hindley-Milner 算法如何工作?
以简单的形式(没有重载),它看起来很干净:
y = arr[x1] //it's Generic. x1: int, arr: T[], y:T
z = y+1// z:int, y:int => T:int, arr: int[]. Oh. All types are solved
但我还没有找到任何关于它如何与重载函数一起工作的解释。
例如:我有 4 个“+”函数重载:
+(int, int):int
+(int64, int64):int64
+(double, double):double
+(any,any):string
例子:
y = x1+ x2 //x1 and x2 can be int32, int64, real, or objects for string concat
z = x1<<2 //oh! it seems x1 is int!
m = not x2 //omg, x2 is bool. That means that y = 2 + true = '2true' i.e. Ty:string
或复杂情况:
//functions:
myfun(x,y) = x<<y //(int,int)->int
myfun(x,y) = "some: " + y.toLower() + not x //(bool,string)-> string
//body:
y1 = myfun(x1,x2) //or (int,int)->int or (bool,string)-> string
y2 = myfun(x3,y1) //or (int,int)->int or (bool,string)-> string
y3 = if (x3) 1 else 0 //x3: bool, y3: string
//x3:bool => y2:string, y1:string
//y1:string=> x1:bool, x2:string
问题是我必须记住所有这些情况:
y1 cases:
int if x1: int and x2:int
string if x1: bool and x2:string
y2 cases:
int if x3: int and y1:int
string if x3: bool and y1:string
y2 案例引用 y1 案例,它看起来像一个方程式树,听起来很吓人。
这种算法是否有任何形式化?