我正在阅读John Barnes的《Ada 2012 编程》 。在第 8.6 节中,他讨论了数组连接和数组边界的规则,特别是:
结果的下限取决于底层数组类型是否受到约束。如果它不受约束...那么下限是左操作数的下限...[否则]下限是数组索引子类型的下限。
然后在 8.6 的练习中,问题 7 如下(我在 [] 内添加了网站 PDF 上给出的答案):
什么是界限:
- 给定
类型 TC 是整数数组 (1..10);
TU 类型是整数的数组(自然范围 <>);
交流:TC;
非盟:TU(1..10);(a) AC(6..10) & AC(1..5) [1..10] (b) AC(6) & AC(7..10) & AC(1..5) [1..10] (c) AU(6..10)& AU(1..5) [6..15] (d) AU(6) & AU(7..10) & AU(1..5) [0..9]
a 和 b 的答案对我来说很有意义,因为 AC 数组是基于一个受约束的类型,我们只使用索引的边界。我认为 c 和应该都是 6..15 的答案,因为基础类型不受约束,最左边的操作数 AU(6) 或 AU(6..10) 将确定起始边界。然后我尝试如下所示对其进行编码以更好地理解,并且所有四个都将边界显示为 1..10。我的代码错了,答案错了还是文本中的描述错了?(顺便说一句,我还使用新的数组变量进行了编码并对这些变量进行了分配,但结果是相同的)。
type TC is array (1..10) of Integer;
type TU is array (Natural range <>) of Integer;
AC: TC;
AU: TU(1..10);
begin
AC := AC(6..10) & AC(1..5);
Tio.Put("7a) Constrained type starting with 6..10 ");
Iio.Put(AC'First); Iio.Put(AC'Last); Tio.New_Line;
Tio.Put ("7b) Constrained type starting with 6 ");
AC := AC(6) & AC(7..10) & AC(1..5); -- 7.b
Iio.Put(AC'First); Iio.Put(AC'Last); Tio.New_Line;
Tio.Put ("7c) Unconstrained type starting with 6..10");
AU := AU(6..10) & AU(1..5);
Iio.Put(AU'First); Iio.Put(AU'Last); Tio.New_Line;
Tio.Put_Line("Answer keys says 6..15");
Tio.Put ("7d) Unconstrained type starting with 6 ");
AU := AU(6) & AU(7..10)& AU(1..5);
Iio.Put(AU'First); Iio.Put(AU'Last); Tio.New_Line;
Tio.Put_Line("Answer key says 0..9 - Why not 6..15???");
(Tio 和 Iio 只是对文本和整数的 std Ada io 包的重命名)
运行时,此代码产生以下控制台输出:
E:\Google Drive\SW_DEV\Ada\Sample\obj\hello
7a) Constrained type starting with 6..10 1 10
7b) Constrained type starting with 6 1 10
7c) Unconstrained type starting with 6..10 1 10
Answer keys says 6..15
7d) Unconstrained type starting with 6 1 10
Answer key says 0..9 - Why not 6..15???