C++20: Pythons range Function, the Second

Contents[Show]

In my last post C++20: Pythonic with the Ranges Library, I started my experiment to implement the beloved Python functions range and filter in C++. Due to two very interesting comments to my last post, I revisit the function range

 

TimelineCpp20

Admittedly, it took me quite a time to become comfortable with the ranges library but the effort paid off. You will see, why. 

I got a few very interesting remarks about my range implementation in my last post. Therefore, I have to visit it once more.

range

As a short reminder. The call range(begin, end, step) generates in Python 2 a list of all integers from begin to end in stepsize steps. begin is inclusive and end is exclusive. step is per default 1.

Over-Engineering

My last range implementation of the last was over-engineered as one of my German readers remarked. The following code snippet shows the over-engineered and the improved version. 

 

std::vector<int> range(int begin, int end, int stepsize = 1) {
    std::vector<int> result{};
    if (begin < end) {                                     
        auto boundary = [end](int i){ return i < end; };    
        for (int i: ranges::views::iota(begin)               // (2)
                  | ranges::views::stride(stepsize) 
                  | ranges::views::take_while(boundary)) {   // (1)
            result.push_back(i);
        }
    }
    else {                                                
        begin++;
        end++;
        stepsize *= -1;
        auto boundary = [begin](int i){ return i < begin; }; 
        for (int i: ranges::views::iota(end)                
                  | ranges::views::take_while(boundary)      
                  | ranges::views::reverse 
                  | ranges::views::stride(stepsize)) {
            result.push_back(i);
        }
    }
    return result;
}  

std::vector<int> range(int begin, int end, int stepsize = 1) {
    std::vector<int> result{};
    if (begin < end) {
        for (int i: ranges::views::iota(begin, end)         // (3)
                 | ranges::views::stride(stepsize)) {
            result.push_back(i);
        }
    }
    else {
        begin++;
        end++;
        stepsize *= -1;
        for (int i: ranges::views::iota(end, begin)         
                  | ranges::views::reverse 
                  | ranges::views::stride(stepsize)) {
            result.push_back(i);
        }
    }
    return result;
}

 

I removed the boundary condition (line 1) in the first implementation and changed the infinite number generator ranges::views::iota(begin) (line 2) to a finite number generator ranges::view::iota(begin, end) (line 3). Consequentially, I did the same in the else branch. 

From range to xrange

The presented range function is eager. It generates a std::vector<int>.  Aleksei Guzev reminded me that Python 2 has also a lazy xrange function which corresponds to the Python 3 range function. He is right. Now, I'm sufficiently comfortable with the ranges library to apply functional concepts to C++. If you are puzzled by the term eager and lazy, read my previous post C++20: Functional Patterns with the Ranges Library

The following example shows a lazy variant of range, which I called, consequentially, xrange

 

// xrange.hpp

#include <range/v3/all.hpp>

template <long long Begin, long long End>           // (3)
auto xrange(int stepsize = 1) {
    if constexpr (Begin < End) {                    // (2)
        return ranges::views::iota(Begin, End)      // (1)
               | ranges::views::stride(stepsize); 
    }
    else {
        long long end  = End + 1;                   // (4)
        long long begin = Begin + 1;                // (4)
        stepsize *= -1; 
        return ranges::views::iota(end, begin)      // (1)
               | ranges::views::reverse 
               | ranges::views::stride(stepsize);
    }
}

This implementation of the lazy xrange function is way more complicated than the previous eager range function. But the added complexity pays off. The following numbers correspond to the numbers in the source code snippet.

  1. The xrange function returns not a std::vector<int> but a composition of views. To ease my job, I let the compiler deduce the return type with auto. Fine, but the return type caused the first challenge. The return types of the if and else branch diver. A function with different return types is not valid C++.
  2. To overcome this issue, I used a C++17 feature: constexpr if. constexpr if allows conditional compilation. When the expression if constexpr (Begin < End)) becomes true, the if branch is compiled; if not, the else branch. In order to be valid, Begin and End have to be constant expressions.
  3. Begin and End are now non-type template parameters which make it possible to use them in a constexpr if (line 2) expression. I used a non-type template parameter of type long long to deal with big numbers. You read in a few sentences, why. 
  4. Constant expressions such as Begin and End can not be modified. Consequentially, I introduced the variables end and begin to adapt the boundaries for the ranges::views::iota call. 

 Let's try it out.

 

// range.cpp

#include "xrange.hpp"

#include <iostream>
#include <range/v3/all.hpp>
#include <vector>

        
int main() {
    
    std::cout << std::endl;

    auto res = xrange<1, 10>();                    // (1)
    for (auto i: res) std::cout << i << " ";
    
    std::cout << "\n\n";
    
    res = xrange<1, 50>(5);                        // (2)
    for (auto i: res) std::cout << i << " ";
    
    std::cout << "\n\n";
    
    auto res2 = xrange<20, 10>(-1);                // (3)
    for (auto i: res2) std::cout << i << " ";
    
    std::cout << "\n\n";
    
    res2 = xrange<50, 10>(-5);                     // (4)
    for (auto i: res2) std::cout << i << " ";
    
    std::cout << "\n\n";
    
    res = xrange<1, 1'000'000'000'000'000'000>();  // (5)
    // for (auto i: res) std::cout << i << " ";    // (6)
    
    
                                                   // (7)
    for (auto i: res | ranges::views::take(10)) std::cout << i << " ";
    
    std::cout << "\n\n";
    
                                                  // (8)
    for (auto i: res | ranges::views::drop_while([](int i){ return i < 1'000'000; })
                     | ranges::views::take_while([](int i){ return i < 1'000'010; })) {
        std::cout << i << " ";
    }
    
    std::cout << "\n\n";
    
}

Lines (1) - (4) shows that the xrange function works as the previous range function. The only difference is that the function arguments become template arguments. When I want to have all numbers up to a quintillion (line 6), I have to kill the program. 

xrangeBreak

Using tics for numbers (1'000'000'000'000'000'000) (line 5) is valid since C++14 and makes the big numbers easier to read. I should not be so eager but lazy. If I ask only for 10 numbers (line 7) or for the numbers between 1'000'000 and 1'000'010 (line 8) the program works like a charm. Only the numbers are generated that are requested.

xrange

What's next?

As I already promised in my last post C++20: Pythonic with the Ranges Library, I present in my next post Python's map function. map empowers you to apply a function to sequences. For convenience reasons, I combine the map and filter function into one function. 

 

 

Thanks a lot to my Patreon Supporters: Meeting C++, Matt Braun, Roman Postanciuc, Venkata Ramesh Gudpati, Tobias Zindl, Marko, G Prvulovic, Reinhold Dröge, Abernitzke, Richard Ohnemus, Frank Grimm, Sakib, Broeserl, António Pina, Markus Falkner, Darshan Mody, Sergey Agafyin, Андрей Бурмистров, Jake, GS, Lawton Shoemake, Animus24, Jozo Leko, and John Breland.

 

Thanks in particular to:   crp4

 

   

Get your e-book at Leanpub:

The C++ Standard Library

 

Concurrency With Modern C++

 

Get Both as one Bundle

cover   ConcurrencyCoverFrame   bundle
With C++11, C++14, and C++17 we got a lot of new C++ libraries. In addition, the existing ones are greatly improved. The key idea of my book is to give you the necessary information to the current C++ libraries in about 200 pages. I also included more than 120 source files.  

C++11 is the first C++ standard that deals with concurrency. The story goes on with C++17 and will continue with C++20.

I'll give you a detailed insight into the current and upcoming concurrency in C++. This insight includes the theory and a lot of practice with more than 140 source files.

 

Get my books "The C++ Standard Library" (including C++17) and "Concurrency with Modern C++" in a bundle.

In sum, you get more than 700 pages full of modern C++ and more than 260 source files presenting concurrency in practice.

 

Get your interactive course

 

Modern C++ Concurrency in Practice

C++ Standard Library including C++14 & C++17

educative CLibrary

Based on my book "Concurrency with Modern C++" educative.io created an interactive course.

What's Inside?

  • 140 lessons
  • 110 code playgrounds => Runs in the browser
  • 78 code snippets
  • 55 illustrations

Based on my book "The C++ Standard Library" educative.io created an interactive course.

What's Inside?

  • 149 lessons
  • 111 code playgrounds => Runs in the browser
  • 164 code snippets
  • 25 illustrations

My Newest E-Books

Course: Modern C++ Concurrency in Practice

Course: C++ Standard Library including C++14 & C++17

Course: Embedded Programming with Modern C++

Course: Generic Programming (Templates)

Course: C++ Fundamentals for Professionals

Subscribe to the newsletter (+ pdf bundle)

Blog archive

Source Code

Visitors

Today 5327

All 4184134

Currently are 103 guests and no members online

Kubik-Rubik Joomla! Extensions

Latest comments