Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Change range adaptor examples to print with formatting ranges #5908

Open
brevzin opened this issue Oct 19, 2022 · 1 comment
Open

Change range adaptor examples to print with formatting ranges #5908

brevzin opened this issue Oct 19, 2022 · 1 comment

Comments

@brevzin
Copy link
Contributor

brevzin commented Oct 19, 2022

Currently, every range adaptor starts with a very short example that prints the contents of an adapted range. For instance, transform has:

vector<int> is{ 0, 1, 2, 3, 4 };
auto squares = views::transform(is, [](int i) { return i * i; });
for (int i : squares)
  cout << i << ' '; // prints 0 1 4 9 16

adjacent has:

vector v = {1, 2, 3, 4};

for (auto i : v | views::adjacent<2>) {
  cout << "(" << std::get<0>(i) << ", " << std::get<1>(i) << ") ";  // prints (1, 2) (2, 3) (3, 4)
}

chunk has:

vector v = {1, 2, 3, 4, 5};

for (auto r : v | views::chunk(2)) {
  cout << '[';
  auto sep = "";
  for (auto i : r) {
    cout << sep << i;
    sep = ", ";
  }
  cout << "] ";
}
// The above prints [1, 2] [3, 4] [5]

We can now change all of these loops (some of which are nested) to just a call to print, which will make the examples smaller and also provide more information. For instance, the adjacent example doesn't actually make clear that it gives you a 2-tuple back. The above can be turned into:

vector<int> is{ 0, 1, 2, 3, 4 };
auto squares = views::transform(is, [](int i) { return i * i; });
print("{}", squares); // prints [0, 1, 4, 9, 16]

and

vector v = {1, 2, 3, 4};
print("{}", v | views::adjacent<2>); // prints [(1, 2), (2, 3), (3, 4)]

and

vector v = {1, 2, 3, 4, 5};
print("{}", v | views::chunk(2)); // prints [[1, 2], [3, 4], [5]]

Is there any reason to not do this?

@jwakely
Copy link
Member

jwakely commented Oct 19, 2022

I think there is some value in the adjacent example which shows that the range elements are tuple-like. It doesn't tell you it's not a tuple with more than 2 elements, but it does show it's something tuple-like. And the chunk example shows you get a range of ranges, not e.g. a range of pairs (I know pairs would be printed differently, but if you don't know that, the suggested replacement "hides" that info).

But I think I still prefer your suggested replacements anyway. They're less cluttered, even if that clutter in the originals has some info about the ranges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants