The abridged TL;DR version is at the bottom.
Act I : Vjalmr Has Issues with Types. Surprise!
For learning Ada I have set out to complete all the Advent of Code challenges, starting from 2015. I skipped day 4, because I am still not comfortable with bit fiddling for an MD5 implementation, so I ended up on day 5.
Here I need to compare some characters, so I thought “Hey! I will just make a Vowel type, and compare the characters that way!”, forgetting all about what I had read here: Wikibook - Characters as Enumeration Literals
This literal ‘A’ has nothing in common with the literal ‘A’ of the predefined type Character (or Wide_Character).
After a lot of digging, which seems to be the norm with this language, I found a blog by one Jim Rogers, who introduced me to subtypes with Static_Predicate
. Just to make sure Mr. Rogers wasn’t pulling my leg, I looked it up in the reference manual, and it was indeed there 3.2.4 Subtype Predicates.
Now, I could create a subtype of Character with only vowels, and compare with my string.
Interlude
Is this the right way of doing it? I know it works, but I am not sure.
Could I cast the character to my type? But if I do that, then all the characters that are not of that type would cause an exception of sorts, if I understand correctly.
Please send your insights, as currently my code looks like the following:
-- Subtype and variable definition, with initialization
subtype Vowels is Character with
Static_Predicate => Vowels in 'a'|'e'|'i'|'o'|'u';
Test_String : String := "I have some vowels in me.";
Vowel_Count : Natural := 0;
-- How many are there?
for C of Test_String loop
if C in Vowels then
Vowel_Count := Vowel_Count + 1;
end if;
end loop;
Act 2: Vjalmr Would Like to Contribute
As enlightening the journey was, finding this information was not as easy as I had hoped. They are actually on the Learn Ada website, but under “Design by contracts”, and also I found it under “Ada for C++ or Java Developer”.
I had not gotten to contracts yet, and I am neither a C++ or Java developer, so I didn’t know to look there. I wanted a type.
Now, the prerequisite for this question is: Am I going about doing it the right way?
If I am, then I would like to add this tidbit to either the WikiBook, or to the ada-lang.io tutorial, which is where I actually got started in the first place - even though there are only two entries.
How would I go about doing this?
Fin
TL;DR
Should I be using Subtype_Predicate
or a unique type for character comparison if I want to see if characters of a string are vowels or not?
If I should use this, could I somehow contribute to the tutorials, or the WikiBook so that this information is easier to find, so the next person who wants to do this doesn’t spend an hour figuring it out?