Ada通用包使用和编译错误“不可见声明”

时间:2014-09-28 05:48:11

标签: generics ada

我是Ada的新手,我正在尝试制作一个通用的quicksort包,它可以采用n个整数数组。数组中的整数必须在1到1000之间。

当我编译以下代码时,它告诉我

main.adb:: "Quicksort" is not visible
main.adb:: non-visible declaration at quick_sort.ads:6
main.adb:: "sort" is undefined

然而,我找不到它之所以如此的原因,它似乎与我在泛型教程中找到的感觉相同。我真的很感激,如果有人能帮助我清楚我为什么会这样,以及如何正确使用通用。

我编写了以下通用包声明和正文。

quick_sort.ads文件

package quick_sort is
generic
    type element_type is private;
    type array_type is array(Natural range <>) of element_type;

    procedure Quicksort(arr: in out array_type);
end quick_sort;

quick_sort.adb文件(摘录)

package body quick_sort is
    procedure Quicksort(arr: in out array_type) is
        left: integer := arr'First;
        right: integer := arr'Last;

        procedure partition is
        ....
        begin
            pivot := find_pivot(arr(left), arr((left+right)/2), arr(right));
            -- do the partition for the array
            while left <= right loop
                while arr(left) < pivot loop
                    left := left + 1;
                end loop;
                while arr(right) > pivot loop
                    right := right - 1;
                end loop;
                if left <= right then
                    swap(arr(left), arr(right));
                    left := left + 1;
                    right := right - 1;
                end if;
             end loop;
        end partition;
    begin
        if arr'Length > 1 then
            partition;
            Quicksort(arr(arr'First..right));
            Quicksort(arr(left..arr'Last));
         end if;
    end Quicksort;
end quick_sort;

main.adb

with quick_sort;
procedure main is

    subtype item is integer range 1..1000;
    arr: array(1..3) of item;
    input: item;
    package sort is new Quicksort(element_type => item);
begin
    for i in 1..3 loop
        get(input);
        arr(i) := input;
    end loop;
    sort(arr);
end main;

编辑:

我尝试使用/不使用“use quick_sort”子句。 无论哪种方式,编译器都会给我以下2个错误

a generic package is not allowed in a use clause
"Quicksort" is not the name of a generic package

我无法弄清楚我是否使用了一些错误的声明者。有什么想法吗?感谢!!!!!

1 个答案:

答案 0 :(得分:2)

Main开始with Quick_Sort;。这意味着Main的代码可以直接访问Quick_Sort但不能直接访问其内容 - 您必须通过说Quick_Sort.<whatever>来限定它们。

您可以使用

开始Main
with Quick_Sort; use Quick_Sort;

或使用

实例化通用
package sort is new Quick_Sort.Quicksort(element_type => item);

解决了"Quicksort" is not visible问题。但是,当您报告时,编译器现在说"Quicksort" is not the name of a generic package;这是真的,因为它是通用过程的名称

当然上面的最后一行应该是

procedure sort is new Quick_Sort.Quicksort(element_type => item);

导致新错误

missing actual "Array_Type"
in instantiation of "Quicksort" declared at yeelan.ada:6
instantiation abandoned

表示而不是

arr: array(1..3) of item;

你需要写一些像

这样的东西
type Item_Array is array (Natural range <>) of Item;
Arr : Item_Array (1 .. 3);

然后

procedure Sort is new Quicksort(Element_Type => Item,
                                Array_Type => Item_Array);

然后你会得到一个关于Get未定义的错误,但其原因将是另一个问题的答案。