Non-contiguous ranges for subtypes in Ada?

2020-03-16 12:48发布

问题:

Totally as an Ada-type-system learning exercise, I was trying to make 3 types (or rather, a type and 2 subtypes):

  • Month_Type, an enumeration of all months
  • Short_Month_Type, a Month_Type subtype only having the months with 30 days
  • February_Month_Type, a subtype with just February

It seems that subtypes must use the range mechanism, correct? (Is there any other kind of subtype?) In order to get it to work with contiguous ranges, I had to put my Month_Type enumeration in this order:

   type Month_Type is (February, April, June, September, November, January, March, May, July, August, October, December);

Obviously this isn't the natural order of months, and I could see people/me trying to do Month_Type'First or something expecting to get January.

So, two general questions from this silly example:

  1. Can I have a subtype that specifies specific components of its base type instead of a range?
  2. Can I somehow hide the implementation detail of the order in which I put months (make 'First not visible, for example)?

Thanks!

回答1:

No, an enumeration subtype only admits a range_constraint in this context, but you could create any number of Sets using Ada.Containers.Ordered_Sets. There are examples here and here.



回答2:

You can make an object that designates only certain values in an enumeration. We would generally call this a "set".

A lot of languages have sets as basic types (along with arrays and records). Of course some don't. Ada is kind of in the middle. It doesn't offically have type named "set" or anything, but boolean operations are defined to work like bitwise logical operations on arrays of boolean. If you pack the array, you get pretty much exactly what other languages' "set" type give you. So Ada does support sets, they are just called "arrays of boolean".

type Month_Set is array (Month) of Boolean;
Short_Month : constant Month_Set := 
    (September => true, April => true, June => true, November => true, 
     February => true, others => false);
Y_Month : constant Month_Set :=
    (January => true, February => true, May => True, July => true, 
     others => false);

-- Inclusion
if (Short_Month(X)) then ...

-- Intersection (Short_Y will include only February)
Short_Y := Short_Month and Month_Ending_in_Y;

-- Union (Short_Y will include All Short_Months and all Y_Months
Short_Y := Short_Month or Month_Ending_in_Y;

-- Negation (Short_Y will include all Short_Months not ending in Y
Shorty_Y := Short_Month and not Month_Ending_in_Y;


回答3:

You can use subtype predicates. In your case:

subtype Short_Month_Type is Month_type with
  Static_Predicate => Short_Month_Type in April | June | September | November


回答4:

Trashgod answered the first question. To answer the second question, make the type itself private.