首页 文章

了解Ada 2012中连锁数组的界限

提问于
浏览
1

我正在阅读John Barnes撰写的Ada 2012编程 . 在8.6节中,他讨论了数组连接和数组边界的规则,特别是:

结果的下限取决于基础数组类型是否受约束 . 如果它不受约束...则下限是左操作数的下限... [否则]下限是数组索引子类型的下限 .

然后在8.6的练习中,问题7如下(我已经在[]内的网站PDF上添加了答案:

给定类型TC是整数的数组(1..10); type TU是Integer的数组(自然范围<>); AC:TC; AU: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数组基于 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???

1 回答

  • 4

    您的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;
    

相关问题