J Cooper
J Cooper

Reputation: 17062

Non-contiguous ranges for subtypes in Ada?

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

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!

Upvotes: 9

Views: 3309

Answers (4)

castle-bravo
castle-bravo

Reputation: 1429

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

Upvotes: 6

trashgod
trashgod

Reputation: 205885

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.

Upvotes: 6

T.E.D.
T.E.D.

Reputation: 44824

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;

Upvotes: 6

Shark8
Shark8

Reputation: 4198

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

Upvotes: 2

Related Questions