今天我在D邮件列表中问了一个问题,是否可以像Ada的wiki页面上的示例那样定义和使用自定义数据类型:
type Day_type is range 1 .. 31;
type Month_type is range 1 .. 12;
type Year_type is range 1800 .. 2100;
type Hours is mod 24;
type Weekday is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday);
type Date is
record
Day : Day_type;
Month : Month_type;
Year : Year_type;
end record;
subtype Working_Hours is Hours range 0 .. 12;
subtype Working_Day is Weekday range Monday .. Friday;
Work_Load: constant array(Working_Day) of Working_Hours
:= (Friday => 6, Monday => 4, others => 10);
而reply则展示了类似以下的内容:
import std.typecons;
import std.exception;
struct Limited(T, T lower, T upper)
{
T _t;
mixin Proxy!_t; //Limited acts as T (almost)
invariant()
{
enforce(_t >= lower && _t <= upper);
}
this(T t)
{
_t = t;
}
}
auto limited(T, T lower, T upper)(T init = T.init)
{
return Limited!(T, lower, upper)(init);
}
unittest
{
enum l = [-4,9];
auto a = limited!(int, l[0], l[1])();
foreach(i; l[0] .. l[1]+1)
{
a = i;
}
assertThrown({a = -5;}());
assertThrown({a = 10;}());
}
这表明虽然可能实现,但很可能会失去Ada的优雅。
现在,在最近了解Nimrod之后,我想知道它如何处理类似任务并确保与Ada相同的类型安全性?