我很想知道是否可以定义我们知道的数据类型,应该是元组,但其长度(或元素数量是不确定的)当前。申请如下:
//I want to declare a data type, one of whose argument is a tuple,
public data MyType=fromListCartesianProduct(tuple<?> product)
//Later I want to instantiate a MyType data by using taking List-CartesianProduct
//instantiate some MyType data
foreach(aTuple in [1,2,3]*["a","b"])
someArr[i]=fromListCartesianProduct(aTuple)
显着的观察结果是,在声明&#34; MyType&#34;时,元组中元素的数量是不确定的。我还可以在流氓脚本中声明这样的类型吗?
作为替代方案,我会将MyType声明为:
public data MyType=fromListCartesianProduct(list[] product)
并在构造特定实例之前将每个元组转换为将笛卡尔积放入列表中。为了清楚起见和其他原因,我想像以前一样定义MyType。
答案 0 :(得分:1)
在原则上答案是否定的。元组具有固定的长度,我们(还)没有行多态。
话虽如此,数据构造函数确实支持不同类型的多态,这可能会有所帮助:
使用关键字参数进行行多态,您可以随时向数据类型添加更多关键字参数,如
data MyType = myCons(int j = 0); // initial decl
data MyType(int k = 1); // extension with another field
重载,您始终可以添加更多具有更多参数的构造函数
data MyType = f(int i); // initial declaration
data MyType = f(int i, int j); // overloaded declaration with more fields
您可以使用make
中的Type
函数根据参数列表动态构造此类构造函数。当然存在运行时类型异常的风险。
处理不可预测类型数据的另一种方法是在类型层次结构中上升一级(让它为value
),然后再次模式匹配你的出路:
list[value] myListRelationOfUnknownType = ...;
for (<int i, int j> <- myListRelationOfUnknownType)
println("printing only pairs of ints: <i> - <j>");
for (<int i, int j, int k> <- myListRelationOfUnknownType)
println("printing only the triples of ints: <i> - <j> - <k>");
这是一种更安全的方式。