我正处于学习Ada并使用它生成具有n个节点的所有不同二叉树的早期阶段。为此,我陷入了尝试初始化数组以存储返回的树实例的麻烦。
with Ada.Text_IO;
procedure Program is
function Factorial(N : in Positive) return Positive is
Answer : Positive := 1;
begin
if N > 1 then
Answer := N * Factorial(N - 1);
end if;
return Answer;
end Factorial;
--TreeNode Declaration
type Tree_Node;
type Tree_Ptr is access Tree_Node;
--TreeNode Definition
type Tree_Node is
record
Left : Tree_Ptr;
Right: Tree_Ptr;
end record;
type TreeList is array (Integer range <>) of Tree_Ptr;
function RecDistinctTree(Start : in Positive; Finish : in Positive; ArraySize : in Positive) return TreeList is
RetList : TreeList(0..ArraySize);
begin
if Start > Finish then
return RetList;
else
for I in Start..Finish loop
declare
LeftChild : TreeList;
RightChild : TreeList;
begin
LeftChild := RecDistinctTree(Start, I - 1);
RightChild := RecDistinctTree(I + 1, Finish);
for J in LeftChild'Range loop
declare
LeftNode : Tree_Ptr;
begin
LeftNode := LeftChild(J);
for K in RightChild'Range loop
declare
RightNode : Tree_Ptr;
NewNode : Tree_Node;
begin
NewNode.Left := LeftNode;
NewNode.Right := RightNode;
-- Make functions for adding to list
end;
end loop;
end;
end loop;
end;
end loop;
end if;
end;
ArraySize : Integer;
N : Integer;
begin
Ada.Text_IO.Put_Line ("Enter # of nodes");
N := Integer'Value(Ada.Text_IO.Get_Line);
ArraySize := (Factorial(2*N) / (Factorial(N+1) * Factorial(N)));
declare
TreeArray : TreeList;
begin
for I in 0..(ArraySize-1) Loop
Ada.Text_IO.Put_Line ("Node!");
end Loop;
end;
end Program;
程序不完整,我只是想了解如何在RecDistinctTree函数中初始化'RetList'。当前,当它编译时,我得到了错误:
program.adb:35:31:不允许不受约束的子类型(需要初始化)
program.adb:35:31:提供初始值或明确的数组边界
我一直在寻找答案,但是与更流行的语言相比,Ada的存在并不多。为什么不简单地实例化Tree_Ptr的ArraySize#数组?也许我没有完全掌握子类型。
答案 0 :(得分:4)
类型TreeList
是不确定的,因为索引范围在类型声明中不受限制:
type TreeList is array (Integer range <>) of Tree_Ptr;
因此,在声明类型为TreeList
的变量时,您必须提供数组边界以约束数组的索引范围(就像您对第一个RetList
声明所做的那样):
RetList : TreeList (0 .. ArraySize); -- This is OK (note that the length of this array will be ArraySize + 1)
或对其进行初始化(例如,使用函数),以便编译器可以从分配的值中推断出索引范围。也许您可以尝试以下方法:
declare
-- ??? Third argument is missing in example.
LeftChild : TreeList := RecDistinctTree (Start, I - 1, ???);
RightChild : TreeList := RecDistinctTree (I + 1, Finish, ???);
begin
[...]