Lu中的运算符重载
在Lu中可以很方便地对运算符进行重载。例如:
thetype(x,y,num,op)=which
{
op<0 : return[newtype()],
op==0 : x-y, //重载运算符+
op==1 : x+y, //重载运算符-
op==2 : x/y, //重载运算符*
nil //该数据类型不支持该运算符的重载,返回nil
};
test(:type,a,b)=
type=thetype(0,0,0,-1), //获取新数据类型
a=cast[3,type], b=cast[5,type], //强制转换为新数据类型
o[" a=",3," b=",5], //输出a和b
o[" a+b=",a+b], //计算并输出a+b,变成了a-b
o[" a-b=",a-b], //计算并输出a-b,变成了a+b
o[" a$b=",a$b]; //没有重载运算符$,故输出nil
结果:
a=3 b=5 a+b=-2 a-b=8 a$b=nil
======
Lu核心库中没有提供矩阵运算,但在脚本中可以通过重载运算符来实现:
outm(x:i,j,m,n)= //输出一个矩阵
{
len[x,0,&m,&n],
i=0, while{i<m,
o["\r\n"], j=0, while{j<n, o[x(i,j)," "], j++},
i++
},
o["\r\n"], x
};
mymatrix(x,y,num,op:c,i,j,k,m,n,u)=which //定义矩阵运算
{
op<0 : return[newtype()],
op==0 : //重载运算符+
{
len[x,0,&m,&n], c=new[reals,m,n].global(),
i=0, while{i<m,
j=0, while{j<n,
c[i,j]=x[i,j]+y[i,j],
j++
},
i++
},
c
},
op==1 : //重载运算符-
{
len[x,0,&m,&n], c=new[reals,m,n].global(),
i=0, while{i<m,
j=0, while{j<n,
c[i,j]=x[i,j]-y[i,j],
j++
},
i++
},
c
},
op==2 : //重载运算符*
{
len[x,0,&m,&n], len[y,0,n,&k], c=new[reals,m,k].global(),
i=0, while{i<m,
j=0, while{j<k,
c[i,j]=0.0,
u=0, while{u<n,
c[i,j]=c[i,j]+x[i,u]*y[u,j], u++
},
j++
},
i++
},
c
},
op==25 ://重载运算符.*
{
len[x,0,&m,&n], c=new[reals,m,n].global(),
i=0, while{i<m,
j=0, while{j<n,
c[i,j]=x[i,j]*y[i,j],
j++
},
i++
},
c
},
op==26 ://重载运算符./
{
len[x,0,&m,&n], c=new[reals,m,n].global(),
i=0, while{i<m,
j=0, while{j<n,
c[i,j]=x[i,j]/y[i,j],
j++
},
i++
},
c
},
nil //该数据类型不支持该运算符的重载,返回nil
};
test(:type,a,b,c)=
type=mymatrix(0,0,0,-1), //获取新数据类型
a=new[reals,2,3,data: 0.,1.,2.,3.,4.,5.], //生成矩阵a
b=new[reals,2,3,data: 1.,2.,3.,4.,5.,6.], //生成矩阵b
c=new[reals,3,2,data: 6.,7.,8.,9.,0.,1.], //生成矩阵c
o["a="], outm(a), o["b="], outm(b), o["c="], outm(c), //输出a、b和c
a=cast[a,type], b=cast[b,type], //强制转换为新数据类型
o["a+b="], outm[a+b], //计算并输出a+b
o["a-b="], outm[a-b], //计算并输出a-b
o["a*c="], outm[a*c], //计算并输出a*c
o["a.*b="],outm[a.*b], //计算并输出a.*b
o["a./b="],outm[a./b]; //计算并输出a./b
结果:
a=
0. 1. 2.
3. 4. 5.
b=
1. 2. 3.
4. 5. 6.
c=
6. 7.
8. 9.
0. 1.
a+b=
1. 3. 5.
7. 9. 11.
a-b=
-1. -1. -1.
-1. -1. -1.
a*c=
8. 11.
50. 62.
a.*b=
0. 2. 6.
12. 20. 30.
a./b=
0. 0.5 0.66666666666666663
0.75 0.80000000000000004 0.83333333333333337