How to std::rotate in Ada?
8 July 2022 at 11:00
Does an equivalent to std::rotate exist in the Ada standard libraries? If not, is there a consensus in the Ada community of some non-standard algorithms library for this sort of operation? I found the Ada Standard Generic Library but it was a proof of concept from 1996 and does not include rotate for arrays (it does for trees, though).
I whittled down the demo on the cppreference page linked above:
#include <algorithm>
#include <iostream>
#include <vector>
auto print = [](auto const& remark, auto const& v) {
std::cout << remark;
for (int n : v)
std::cout << n << ' ';
std::cout << '\n';
};
int main()
{
std::vector<int> v{2, 4, 2, 0};
print("before rotate:\t\t", v);
// simple rotation to the left
std::rotate(v.begin(), v.begin() + 1, v.end());
print("simple rotate left:\t", v);
// simple rotation to the right
std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
print("simple rotate right:\t", v);
}
The equivalent Ada would be this, if I had a drop-in replacement for the std::rotate
calls:
with Ada.Text_IO;
with Ada.Characters;
with Ada.Characters.Latin_1;
procedure Main is
Tab : Character renames Ada.Characters.Latin_1.HT;
type Number_List_Type is array (1 .. 4) of Integer;
procedure Print (Remark : String; Numbers : Number_List_Type) is
use Ada.Text_IO;
Endline : Character renames Ada.Characters.Latin_1.LF;
begin
Put (Remark);
for N of Numbers loop
Put (N'Image & ' ');
end loop;
Put (Endline);
end;
V : Number_List_Type := (2, 4, 2, 0);
begin
print("before rotate:" & Tab & Tab, v);
-- simple rotation to the left
-- std::rotate(v.begin(), v.begin() + 1, v.end());
print("simple rotate left:" & Tab, v);
-- simple rotation to the right
-- std::rotate(v.rbegin(), v.rbegin() + 1, v.rend());
print("simple rotate right:" & Tab, v);
end Main;
Expected output:
before rotate: 2 4 2 0
simple rotate left: 4 2 0 2
simple rotate right: 2 4 2 0