了解 Ada 2012 中串联数组的边界

Understanding bounds of concatenated arrays in Ada 2012

我正在阅读 John Barnes 的 Programming in Ada 2012。在 8.6 节中,他讨论了数组连接和数组边界的规则,特别是:

The lower bound of the result depends on whether the underlying array type is constrained or not. If it is unconstrained...then the lower bound is that of the left operand...[otherwise] the lower bound is that of the array index subtype.

那么在8.6的习题中,第7题如下(我在[]里面添加了网站PDF给出的答案):

  1. Given

    type TC is array (1..10) of Integer;
    type TU is array (Natural range <>) of Integer;
    AC: TC;
    AU: TU(1..10);

What are the bounds of:

(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 数组基于 constrained 类型,我们只使用索引的边界。我认为 c 的答案应该都是 6..15,因为基础类型是 unconstrained 最左边的操作数 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???

您的 AU 被定义为从下限 1(范围为 1..10 的匿名数组子类型)开始。那将永远改变。

对于不受约束的结果(c 和 d),您应该分配给一个新变量,如下所示:

declare
   AU_c : TU := AU(6..10) & AU(1..5);
   AU_d : TU := AU(6) & AU(7..10)& AU(1..5);
begin
   -- your Put/Put_Lines here
end;