5 ada
我正在学习 ada,并且正在尝试为枚举实现加法重载。
基本上我希望能够将 Integer 添加到 Day 类型并获取结果 Day 值。所以星期一 + 2 => 星期三。
这是我的简化代码:
procedure overload is
type Day is (
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
);
day1 : Day := Monday;
function "+" (left: Day; right: Integer) return Day is
-- how would I handle this here? I want to basically say
-- if Day + Integer > Saturday then
-- wraparound back to Sunday
return DayValue;
begin
for x in 0 .. 7 loop
Ada.text_io.put_line("Monday + " & Integer'Image(x) & " = " & Day'Image(day1 + x));
end loop;
end overload;
Run Code Online (Sandbox Code Playgroud)
您可以使用 'Pos 和 'Val 属性来完成此操作。'Pos 返回所提供的日期相对于第一个选项(0 索引)的位置,而 'Val 接受 Pos 值并返回日期类型值:
return Day'Val(Day'Pos(Left) + Right);
Run Code Online (Sandbox Code Playgroud)
对于环绕检查,请检查“星期六的 Pos 值”与“左侧的 Pos 值+右侧值,并使用 Day”Val(0) 表示星期日
或者将 Right 的输入类型从 Integer 切换为 Natural 并使用模数数学:
return Day'Val((Day'Pos(left) + Right) mod 7);
Run Code Online (Sandbox Code Playgroud)
你甚至可以想象一下,为 7 设置一个常数:
Day_Mod : constant := Day'Pos(Day'Last) - Day'Pos(Day'First) + 1;
Run Code Online (Sandbox Code Playgroud)
然后就变成了
return Day'Val((Day'Pos(left) + Right) mod Day_Mod);
Run Code Online (Sandbox Code Playgroud)