设计语言类型系统的正确类设计
我正在为自己的目的设计一种语言。它基本上有两个实体:功能和类型。例如,
Object1 = CreateObject1("param1", "param2", 23 ) //Line 1
Object3 = Object1 + Object2 //Line 2
Evaluate(Object3) //Line 3
第2行评估Object1类型的对象是否为Object2的“+”,如果是,则将创建结果对象并将其分配给Object3。变量定义就像 JavaScript 中的 var 关键字。
我心中的设计就像创建一个基本的“值”类(具有加、减、乘、除等基本操作),每个子对象对应于我计划在语言中摄取的不同类型。
class Value{
Value add(Value value)
..
}
class Integer extends Value{
Value add(Value value){
//if value is compatible to add with Integer type then return the appropriate
//resultant object else throw exception.
}
}
我可以轻松创建这样的子类,但是如果函数更改了对象的属性(例如更改类的成员值),那么我需要将其向下转换为该类型并更新适当的属性。
class ABC extends Value{
Value add(Value value){
//
}
private int X;
private int Y;
private int Z;
private string XYZ;
public setX(int x){
this.X = x;
}
.
.
}
ObjectABC = GetABC();
SetX(ObjectABC, 1)
在函数SetX()的实现中。我会做这样的事情:
ABC abc = (ABC)ObjectABC; //ObjectABC will be a Value type here.
abc.setX( 1 );
我想摆脱这种令人沮丧的事情。能做到吗?请指教。
I am designing a language for my own purposes. It will have two entities basically, functions and types. e.g.
Object1 = CreateObject1("param1", "param2", 23 ) //Line 1
Object3 = Object1 + Object2 //Line 2
Evaluate(Object3) //Line 3
Line 2 evaluates if object of type Object1 be "+" to Object2 and if yes then a resultant object will be created and will be assigned to Object3. The variable definitions are like var keyword in Java Script.
The design in my mind is like creating a base "Value" class (having primitive operations like add, subtract, multiply, divide etc) having concrete children each corresponding to different types which I plan to ingest in the language.
class Value{
Value add(Value value)
..
}
class Integer extends Value{
Value add(Value value){
//if value is compatible to add with Integer type then return the appropriate
//resultant object else throw exception.
}
}
I can create children classes like that easily but if a function changes the attributes of a object (like a member value be changed of a class) then I need to downcast to it to that type and update the appropriate property.
class ABC extends Value{
Value add(Value value){
//
}
private int X;
private int Y;
private int Z;
private string XYZ;
public setX(int x){
this.X = x;
}
.
.
}
ObjectABC = GetABC();
SetX(ObjectABC, 1)
In the implemenatiob of the function SetX(). I will be doing something like this:
ABC abc = (ABC)ObjectABC; //ObjectABC will be a Value type here.
abc.setX( 1 );
I want to get rid of this down casting thing. Can it be done? Please advise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像这样使用双重调度:
You could use double dispatch like so: