变体记录:多次使用组件

时间:2018-03-28 20:54:33

标签: ada

我创建了以下示例代码:

type Category is (A, B, C);

type My_Record (The_Category : Category) is record
    case The_Category is
        when A =>
            A : Natural;
        when B =>
            B : Integer;
        when C =>
            A : Natural;
            B : Integer;
    end case;
end record;

代码显然在Ada中无效,因为我收到两个编译器错误:"A/B" conflicts with declaration at line ...

为什么Ada不支持这种变体记录的定义?我认为它可能有用。是否有其他方法来模拟这种数据结构?

2 个答案:

答案 0 :(得分:1)

不支持它,因为它可能会使读者(或开发者)感到困惑。

不同分支中的字段在逻辑上是不同的字段,因此使用相同的名称会令人困惑。

(这是我的解释。如果有正式的,你可以在Ada 83 Rationale找到它。)

我练习你做这样的事情:

type Categories is (A, B, C);

type Data (Category : Categories) is record
   case Category is
      when A =>
         Identifier_1 : Natural;
      when B =>
         Identifier_2 : Integer;
      when C =>
         Identifier_3 : Natural;
         Identifier_4 : Integer;
      end case;
   end record;

你必须自己提出一些实际的,明智的命名,因为我不知道你正试图解决哪个问题。

答案 1 :(得分:1)

我最近遇到了这个问题。这是Ada背后的情况。 Adaic(Pythonic等价?)的方式类似于:

type Category is (A, B, C);
type A_Data is
    record
        A : Natural;
    end record;
type B_Data is
    record
        B : Integer;
    end record;
type C_Data is
    record
        A : Natural;
        B : Integer;
    end record;

type My_Record (The_Category : Category) is record
    case The_Category is
        when A =>
            A : A_Data;
        when B =>
            B : B_Data;
        when C =>
            C : C_Data;
    end case;
end record;

虽然详细,但它提供了有关您有权访问的内容的强类型。用法几乎相同,主要区别在于C类的东西看起来是统一的:

case My_Object.The_Category is
    when A => 
        Use_Integer (My_Object.A.A);
    when B => 
        Use_Natural (My_Object.B.B);
    when C =>
        Use_Integer (My_Object.C.A);
        Use_Natural (My_Object.C.B);
end case;

很多人花时间习惯阿达的冗长,但随着时间的推移你会学会喜欢它。这个更大的接口编译成几乎完全相同的代码,并且对可扩展性更加开放(如果类别A项目现在也需要浮点数而不是更改所有A类别项目,只需更改A_Data类型)。

相关问题