Category: ranges

  • Range Comprehensions

    I’ve been busy since I last wrote about ranges. I have a lot of news to share, but in this post, I’m going to narrowly focus on a recent development that has me very excited. It’s a new feature that I’m calling range comprehensions, and they promise to greatly simplify the business of creating custom ranges.

    List Comprehensions

    If you’re familiar with list comprehensions from Haskell or Python, your ears might have pricked up when I said “range comprehensions.” List comprehensions give you a pithy way to generate new lists from existing ones, either by transforming thenm, filtering them, or combining them, or whatever. Here, for instance, is a Haskell program for generating the first 10 Pythagorean triples:

    main = print (take 10 triples)
    
    triples = [(x, y, z) | z <- [1..]
                         , x <- [1..z]
                         , y <- [x..z]
                         , x^2 + y^2 == z^2]
    

    The way to read the triples line is this: generate a list of tuples (x, y, z) where z goes from 1 to infinity, x goes from 1 to z (inclusive), and y goes from x to z, but only yield those triples for which x^2 + y^2 == z^2 is true. The code then generates every combination of x, y, and z in the specified ranges in some order and filters it, yielding a list of the Pythagorean triples. Beautiful. Of particular interest is the fact that, since Haskell is lazy, there is no problem with a comprehension that generates an infinite list.

    Back-Story

    Back in October, I published a blog post about API design and std::getline in which I showed how a range-based interface is better than the existing one. My friend Bartosz Milewski commented that ranges are difficult to work with and challenged me to show the range-based equivalent of the above pithy Haskell program. I admit that at the time, I had no answer for Bartosz.

    Recently, Bartosz published a blog post about just this problem. In his post, Bartosz describes some pretty simple results from category theory (if any category theory can be described as “simple”), and applies it to the problem of generating the Pythagorean triples lazily in C++. It’s a great post, and you should read it. Here, finally, was my answer. Although Bartosz’s code was terribly inefficient, somewhat difficult to reason about, and not formulated in terms of STL-ish concepts, I knew the direction I had to take.

    Introducing Range Comprehensions

    Without further ado, here is my solution to the Pythagorean triples problem:

    using namespace ranges;
    
    // Lazy ranges for generating integer sequences
    auto const intsFrom = view::iota;
    auto const ints = [=](int i, int j)
        {
            return view::take(intsFrom(i), j-i+1);
        };
    
    // Define an infinite range of all the Pythagorean
    // triples:
    auto triples =
        view::for_each(intsFrom(1), [](int z)
        {
            return view::for_each(ints(1, z), [=](int x)
            {
                return view::for_each(ints(x, z), [=](int y)
                {
                    return yield_if(x*x + y*y == z*z,
                        std::make_tuple(x, y, z));
                });
            });
        });
    
    // Display the first 10 triples
    for(auto triple : triples | view::take(10))
    {
        std::cout << '('
            << std::get<0>(triple) << ','
            << std::get<1>(triple) << ','
            << std::get<2>(triple) << ')' << '\n';
    }
    

    Lines 4 and 5 define intsFrom and ints, which are lazy ranges for generating sequences of integers. Things don’t get interesting until line 12 with the definition of triples. That’s the range comprehension. It uses view::for_each and yield_if to define a lazy range of all the Pythagorean triples.

    view::for_each

    What is view::for_each? Like std::for_each, it takes a range and function that operates on each element in that range. But view::for_each is lazy. It returns another range. The function that you pass to view::for_each must also return a range. Confused yet?

    So many ranges, but what’s going on? Conceptually, it’s not that hard. Let’s say that you call view::for_each with the range {1,2,3} and a function f(x) that returns the range {x,x*x}. Then the resulting range will consist of the elements: {1,1,2,4,3,9}. See the pattern? The ranges returned by f all got flattened. Really, range flattening is all that’s going on.

    Now look again at line 12 above:

    auto triples =
        view::for_each(intsFrom(1), [](int z)
        {
            return view::for_each(ints(1, z), [=](int x)
            {
                return view::for_each(ints(x, z), [=](int y)
                {
                    return yield_if(x*x + y*y == z*z,
                        std::make_tuple(x, y, z));
                });
            });
        });
    

    For every integer z in the range 1 to infinity, we call view::for_each (which, recall, returns a flattened range). The inner view::for_each operates on all the integers x from 1 to z and invokes a lambda that captures z by value. That function returns the result of a third invocation of view::for_each. That innermost lambda, which finally has x, y, z, makes a call to a mysterious-looking function that is provocatively named yield_if. What’s that?

    yield_if

    The semantics of yield_if is to “inject” the tuple (x,y,z) into the resulting sequence, but only if is a Pythagorean triple. Sounds tricky, but it’s really very simple. Recall that the function passed to view::for_each must return a range. Therefore, yield_if must return a range. If the condition x*x + y*y == z*z is false, it returns an empty range. If it’s true, it returns a range with one element: (x,y,z). Like I said, simple. There’s also a function called yield that unconditionally returns a single-element range.

    Now that you know how it works, you can forget it. You can just use view::for_each and yield_if as if you were writing a stateful function that suspends itself when you call yield or yield_if, kind of like a coroutine. After all, I picked the name “yield” to evoke the yield keyword from C#. That keyword gives the function it appears in precisely those coroutine-ish semantics. What’s more, C# functions that have yield statements automatically implement C#’s IEnumerable interface. IEnumerable fills the same niche as the Iterable concept I’ve described in previous posts. That is, you can loop over the elements.

    For instance, in C# you can do this (taken from Wikipedia):

    // Method that takes an iterable input (possibly an
    //  array) and returns all even numbers.
    public static IEnumerable<int>
    GetEven(IEnumerable<int> numbers) {
        foreach(int i in numbers) {
            if((i % 2) == 0) {
                yield return i;
            }
        }
    }
    

    With range comprehensions, equivalent code looks like this:

    auto GetEvens =
        view::for_each(numbers, [](int i)
        {
            return yield_if((i % 2) == 0, i);
        });
    

    That’s darn near the same thing, and we don’t need any special keyword or compiler magic.

    Performance

    Ranges that return ranges that return ranges, oy vey. How horribly does it perform at runtime? As it turns out, not horribly at all, but a lot depends on how good your optimizer is.

    I wrote a simple benchmark program that iterates over the first 3000 triples and does some trivial computation with them. I do this in two ways. One is with the range comprehension above, and the other is with this triply-nested for loop:

    for(int z = 1;; ++z)
    {
        for(int x = 1; x <= z; ++x)
        {
            for(int y = x; y <= z; ++y)
            {
                if(x*x + y*y == z*z)
                {
                    result += (x + y + z);
                    ++found;
                    if(found == 3000)
                        goto done;
                }
            }
        }
    }
    done:    
    

    You would expect this solution to fly and the range-based one to crawl. But here are the numbers using a hot-off-the-presses gcc-4.9 with -O3:

    Raw loop:             2.2s
    Range comprehension:  2.3s
    

    That’s it?! Yes, all that extra work being done by the range comprehension is totally transparent to the optimizer, which generates near-optimal code. Kind of amazing, isn’t it?

    If, however, your compiler of choice is clang, I have some bad news for you. The range comprehension is (wait for it) 15 times slower. Dear god, that’s awful. I guess that goes to show that despite the astounding awesome-ness of clang in most respects, its optimizer still has some ways to go.

    Summary

    Haskell and Python have list comprehensions. C# has LINQ and yield. And now C++ has range comprehensions. It’s now pretty trivial to generate non-trivial sequences on the fly, lazily and efficiently, in a way that plays well with all the STL algorithms. Like I said, I’m pretty excited.

    Acknowledgements

    My deep thanks to Bartosz Milewski for getting me 90% of the way there. I couldn’t have done this without his insights, and the insights of all the functional programmers and category theoreticians that came before. Math FTW!

    "\e"
    "\e"
    "\e"
  • Range Concepts, Part 4 of 4: To Infinity And Beyond

    Last time, I introduced a new concept, Iterable, and showed how it solved many of the problems with pair-of-iterator-style ranges. This time around, I’m going to extend Iterable in small ways to make programming with infinite ranges safer and more efficient. Disclaimer: The ideas in this post are more speculative than in the previous three. I’m looking forward to the discussion.

    Quick Recap

    Previously I described the problems that crop up when representing infinite and delimited ranges with pairs of iterators, the first three of which are:

    1. Iteration is slow
    2. The ranges are forced to model a weaker concept than they could otherwise
    3. Their implementations are awkward

    My solution to that problem is the Iterable concept; that is, to allow the end of the range to have a different type than the beginning of the range. Once you allow that:

    1. Performance is improved because sentinel-ness is encoded in the C++ type system and so doesn’t need to be check at runtime.
    2. The concept a range can model is no longer limited by the concept that can be modeled by the sentinel, which by its very definition cannot be decremented or dereferenced.
    3. Since sentinel-ness is now a compile-time property and does not need to be explicitly checked, the logic of iterator comparisons is simpler.

    There were two more issues that crop up with infinite ranges in particular. They are:

    1. Some STL algorithm just don’t work with infinite ranges
    2. Infinite or possibly-infinite ranges will overflow their difference_type

    These are the issues I’ll focus on in this post.

    Infinite Iterables

    iota_range is an infinite ranges of integers, starting at some value and counting up, forever. (Suppose that iota_range uses an infinite-precision integer type, so it really never ends.) It is a sorted forward range. Binary search algorithms work with sorted forward ranges, so they should work with iota_range, right? Wrong! You can’t conquer infinity by dividing it. (You can quote me on that.)

    Can we make the standard algorithms safer, so the algorithms that don’t work with infinite ranges fail to compile if you pass them one? In the current formulation of the STL the answer is no. There’s no way, given two iterators of the same type, to tell at compile time if they denote an infinite range. Think about it for a minute: the following is perfectly ok, and guaranteed to finish:

    // OK, this finishes quickly
    iota_range<bigint> rng;
    auto i = std::lower_bound(rng.begin(),
                              std::next(rng.begin(), 10),
                              5);
    

    But the following will run forever:

    // Oops! this runs forever. :'-(
    iota_range<bigint> rng;
    auto i = std::lower_bound(rng.begin(),
                              rng.end(),
                              5);
    

    If rng.begin() is the same type as rng.end(), those two calls resolve to the same instantiation of lower_bound. There’s no way for lower_bound to tell whether it’s going to run forever or not. But if we allow the sentinel type to be different, it opens the door to greater compile-time checking. How? Suppose we had a type function (aka a metafunction) called DenotesInfiniteSequence that takes a type pair (BeginType, EndType) and says whether the sequence is infinite or not. We’ve already established that if BeginType and EndType are the same, DenotesInfiniteSequence has to always return false since it can’t know. But if they’re different — say, if EndType is a special type called unreachable_sentinel or something — then we can know at compile-time that the sequence is infinite.

    So the Iterable concept naturally give us a way to test for infinite ranges, right? Well…

    Infinite Ranges

    Some ranges might genuinely be infinite even though their begin and end iterators have the same type. We want to catch those, too. Consider:

    // An infinite range of zeros
    class zeros : public range_facade<zeros>
    {
        friend range_core_access;
        struct impl
        {
            bool sentinel;
            int current() const { return 0; }
            void next() {}
            bool equal(impl that) const
            { return sentinel == that.sentinel; }
        };
        // begin() and end() are implemented by range_facade
        // in terms of begin_impl and end_impl. They will 
        // have the same type.
        impl begin_impl() const { return {false}; }
        impl end_impl() const { return {true}; }
    };
    // zeros models the Range concept
    CONCEPT_ASSERT(Range<zeros>());
    
    int main()
    {
        // Oops! This will run forever.
        for_each(zeros(), [](int i) {/*...*/});
    }
    

    We’d like to be able to catch mistakes like this if it’s possible, but clearly, the binary DenotesInfiniteSequence type function we hypothesized above isn’t up to the task. For zeros, the types BeginType and EndType are the same, so DenotesInfiniteSequence would return false. And yet zeros is infinite.

    So instead of a DenotesInfiniteSequence type function that takes a (BeginType,EndType) pair, let’s have a unary IsInfinite type function that takes a range type. What could be simpler? In code, it would be a type trait:

    // Report whether an Iterable is infinite or not
    template<typename Iterable>
    struct is_infinite
      : std::integral_constant<bool, true-or-false>
    {};
    

    This type trait can be used to define a concept FiniteIterable as follows:

    // Current proposed Concept Lite syntax
    template<typename T>
    concept bool FiniteIterable =
        Iterable<T> && !is_infinite<T>::value;
    

    (Why FiniteIterable instead of InfiniteIterable? I’ll say why in a minute.) Every FiniteIterable is an Iterable. In fact, there’s a parallel refinement hierarchy here, just as there is with Ranges:

    Finite Iterable Concept Hierarchy

    Finite Iterable Concept Hierarchy

    And as with Range, we don’t actually need to define all these concepts in code. “Finite-ness” is orthogonal to the Iterable concept hierarchy and can be queried separately.

    So why FiniteIterable instead of InfiniteIterable? It comes down to the algorithms and their requirements. There are no algorithms that require that their range arguments be infinite. So being able to say requires InfiniteIterable<T> is useless. But an algorithm like lower_bound would very much like to require that the range it’s operating on has a definite end; hence FiniteIterable.

    Now, all iterable things model FiniteIterable by default, and a type has to opt in to being infinite. How? One way is to specialize is_infinite. As a convenience, the utilities for building iterables and ranges take an optional IsInfinite template parameter, so opting in is easy. Here’s how zeros looks now:

    // An infinite range of zeros
    class zeros : public range_facade<zeros, true>
    {   // ... IsInfinite ...................^^^^
        // ... as before ...
    };
    // zeros is a Range but it's not Finite
    CONCEPT_ASSERT(Range<zeros>());
    CONCEPT_ASSERT(!FiniteIterable<zeros>());
    

    With the addition of the FiniteIterable concept, the algorithms that require finite-ness have an easy way to check for it at compile-time. This is only possible with a range-based interface, so we can add that to the long list of advantages ranges have over iterators.

    Possibly Infinite Ranges

    Once we have a way to separate the finite ranges from the infinite, we now have to categorize the ranges. This should be simple; either a range is finite or it’s not, right? It’s actually trickier than that. Take an istream range, for instance. It might be infinite, or it might not. You don’t know. Most of the time, the stream runs dry eventually and the iteration stops. In fact, almost all the time. But sometimes…

    This is a sticky situation. Should we be prevented from passing an istream range to an algorithm just because it might go on forever? I think the answer is yes, but I confess I haven’t made up my mind about that yet. I think we need more real-world usage.

    Counting the Uncountable

    With infinite ranges, we run into an inherent difficulty: all iterators — and by extension, all iterables — have an associated difference_type. Alex Stepanov has this to say about an iterator’s difference_type:

    DistanceType returns an integer type large enough to measure any sequence of applications of successor allowable for the type. 1

    Since an iterator over an infinite sequence permits an infinite number of applications of successor, we need an integer type large enough … well, infinitely large. Does this problem have a solution? As in the words of Tevye from Fiddler on the Roof, “I’ll tell you…. I don’t know.”

    No flash of insight has been forthcoming. Instead, here’s a core dump of my brain on the issue:

    1. C++ needs bigint, an infinite-precision integral type. Other languages have it. C++ is a great language for building libraries, and this is crying out for a library solution. If such a type existed, an infinite range might choose that as its difference_type. That would come with a not-insignificant performance hit.
    2. Infinite ranges could use safe_int as its difference_type. safe_int behaves like an int, but it can represent infinity. Instead of overflowing and going into undefined-behavior-land, a safe_int clips to infinity and stays there. The two biggest problems with letting an iterator’s difference_type overflow are undefined behavior and the inability to tell after the fact if anything went wrong. With safe_int, you can avoid the UB and have a way to tell at runtime if something bad happened. That might be enough in some situations. If this feels like a Big Hack to you, that’s because it is.
    3. An alternate design of safe_int might be to throw an exception on overflow rather than clip to infinity. That might be appropriate in some situations.
    4. Another approach is to look at where the library uses difference_type and give users a way to specify that a different type be used. For instance, the API of a range-based distance algorithm might take a range and optionally a starting count. It would default to difference_type{0}, but if you passed in, say, a bigint then you’re opting in to safer, slower code.
    5. You can ignore the problem. Users that worry about overflow can use a counted range adaptor to make sure iteration stops before the difference_type overflows.
    6. Something else I haven’t thought of.

    Here’s my opinion: I don’t like anything that introduces unnecessary runtime overhead, so std::ptrdiff_t is an acceptable default for difference_type. In addition, we should design range-based interfaces in such a way as to give users a way to specify a different difference_type when overflow is a concern. So basically, I’m going with options (4) and (5). The other library types — bigint and maybe a policy-based safe_int — would be nice-to-haves that users could pass to these algorithms to get the safety/speed tradeoff that makes sense for them.

    That’s the best I’ve got.

    Summary, and Next Steps

    Maybe after the first 3 posts about range concepts you were feeling good, like it’s all falling into place, and now you’re kind of confused. But I think we’re in a good place, much better than we were. I described 5 problems with pair-of-iterator ranges. A new concept — Iterable — addresses 3 of them very well (slow iteration, modeling weaker-than-necessary concepts, awkward implementations). The 4th problem (infinite ranges) we can address with a further refinement of Iterable. And we have some options for dealing with the 5th (overflow), which is helped by being able to tell the infinite ranges apart from the finite ones. So the new concepts help there too. I think this is a promising start.

    Some of you have asked if I’m planning to take these ideas to the C++ standardization committee. Indeed, I am. When we get language support for concepts (not if, when), there is very likely to be a push for a new, concept-ified version of the STL, probably in a different namespace. This wholesale rewrite is a prime opportunity for getting something like Iterable baked into the STL from day one.

    My next step is to start a discussion on the SG9 (Ranges) mailing list. It’s likely to be contentious, and I expect these ideas will evolve. Consider subscribing to the list and joining the discussion.

    Addendum

    Sean Parent has commented on my blog and made an interesting point about the importance of counted algorithms (e.g. copy_n). He’s challenged me to find a more efficient way of supporting counted ranges than my proposed solution. I have some initial thoughts on the issue that I’ll write up and publish here provided they pan out. At any rate, it’s clear that it’s time for brains other than mine to be working on this problem. C++17 is closer than you might think, and time’s a’wasting!

    x

    1. Stepanov, A; McJones, P. Elements of Programming. Addison-Wesley. 2009.↩

  • Range Concepts, Part 3 of 4: Introducing Iterables

    In the last two blog posts, I describes the challenges I’ve encountered while building a next-generation range library. In this post, I’ll sketch for you my proposed solution: refinements of the range concepts that allow delimited, infinite, and pair-o’-iterator-style ranges to fit comfortably within the concept hierarchy without loss of performance or expressive power and with increased safety. I’ve built a range library around these concepts that subsumes and extends all of the C++98 STL algorithms and the Boost.Range adaptors, so I can say with confidence that these concepts lead to a useful and consistent generic range library.

    Recap

    At the end of my last post, I summed up the issues of pair-o’-iterators (PoI)-style ranges as follows:

    • Delimited and infinite ranges generate poor code
    • These range types are sometimes forced to model weaker concepts than they might otherwise
    • Use of infinite ranges with some algorithms is unsafe
    • Delimited and infinite ranges are harder to implement than they need to be
    • Ranges that are possibly infinite can overflow their difference_type

    The first issue is particularly hard to swallow, so it’s where I’ll focus my energy in this post.

    The Range Concept

    Before I go any further, let’s be a little more formal about what “range” means. The C++ standard uses the word “range” all over the place without formally defining it. But we can infer from the section [iterator.range] that a range is something on which you can call begin and end to get back a pair of iterators where the end is reachable from begin. In the language of the current “Concepts Lite” proposal, we can formalize the Range concept as follows:

    using std::begin;
    using std::end;
    
    template<typename T>
    using Iterator_type =
        decltype(begin(std::declval<T>()));
    
    template<typename T>
    concept bool Range =
        requires(T range) {
            { begin(range) } -> Iterator_type<T>;
            { end(range) }  -> Iterator_type<T>;
            requires Iterator<Iterator_type<T>>;
        };
    

    This basically says that you can call begin and end on a range and that you get back iterators. There are refinements of the Range concept (not shown) called InputRange, ForwardRange, etc. that merely require more of their iterators. The refinement hierarchy is shown below. It’s fairly straightforward. (The above syntax was given to me by Andrew Sutton, the author of the Concepts Lite proposal, shortly after the February 2014 standardization committee meeting, so it’s guaranteed fresh. He warns me that the syntax may yet change in the future.)

    Range Concept Hierarchy

    Range Concept Hierarchy

    These concepts are the foundation of the Boost.Range library.

    Problem 1: Poor Code Generation

    If you recall, to implement delimited and infinite ranges as a pair of iterators, the end iterator must be some sort of sentinel iterator. A sentinel represents a conceptual position rather than a physical one. You can still think of it as the last-plus-one position, the only difference is that you won’t know the physical position until you reach it. Since the sentinel has the same type as the iterator, it requires a runtime test to determine whether a given iterator is the sentinel or not. This leads to slow iterator comparisons and awkward range implementations.

    The Iterable Concept

    Think of the things you do with iterators. You increment them, you dereference them, and you compare them for equality, right? What can you do with a sentinel iterator? Not much. You can’t change its position since it represents a conceptual position, not a physical one. You can’t dereference them, because they always stand in for the last-plus-one position, which is not dereferencable. But you can compare it to an iterator. In other words, a sentinel is a very weak iterator.

    The trouble with delimited and infinite ranges comes from trying to make a sentinel iterator into a regular iterator. It just isn’t one, and making it so causes problems. So just let it be. In other words:

    Let range sentinels have different types than their ranges’ iterators.

    The Range concept requires the begin and end iterator have the same type. If I allow the types to differ, I’m talking about something weaker than Range: the Iterable concept. Iterables are just like Ranges except the begin and end types differ. Here’s the Iterable concept:

    template<typename T>
    using Sentinel_type =
        decltype(end(std::declval<T>()));
    
    template<typename T>
    concept bool Iterable =
        requires(T range) {
            { begin(range) } -> Iterator_type<T>;
            { end(range) }  -> Sentinel_type<T>;
            requires Iterator<Iterator_type<T>>;
            requires EqualityComparable<
                Iterator_type<T>, Sentinel_type<T>>;
        };
    
    template<typename T>
    concept bool Range =
        Iteratable<T> &&
        Same<Iterator_type<T>, Sentinel_type<T>>;
    

    All Ranges are Iterables trivially. That is, the Range concept refines Iterable by adding one additional constraint: that begin and end have the same type. In fact, the Iterable concept hierarchy parallels the Range hierarchy nicely:

    Iterable Concept Hierarchy

    Iterable Concept Hierarchy

    This is what the hierarchy looks like when considering Ranges, Iterables, and Iterators, but it’s not necessarily the way we would actually define these concepts in our code. Notice that “rangeyness” — that is, whether begin and end have the same type — is orthogonal to the strength of the begin iterator. When we want to require that a type model RandomAccessRange, we can say requires RandomAccessIterable<T> && Range<T> and do away with the other Range concepts entirely.

    The difference between, say, a BidirectionalIterable and a ForwardIterable is in the concept modeled by the Iterable’s begin iterator. If the EqualityComparable constraint in the Iterable concept gives you pause, read on. I justify it below.

    Iterables and the STL Algorithms

    “But wait,” you say. “No STL algorithms will work with Iterables because they expect begin and end to have the same type!” That’s sadly true. So I went through all the STL algorithm to see which could be re-implemented in terms of the weaker concept. Take std::find for example:

    template<class InputIterator, class Value>
    InputIterator
    find(InputIterator first, InputIterator last,
         Value const & value)
    {
        for (; first != last; ++first)
            if (*first == value)
                break;
        return first;
    }
    

    Today, std::find requires Ranges. But notice how this algorithm never tries to change the position of the end iterator. The find algorithm can very easily be changed to work with Iterables instead of Ranges:

    template<class InputIterator, class Sentinel, class Value>
    InputIterator
    find(InputIterator first, Sentinel last,
         Value const & value)
    {
        for (; first != last; ++first)
            if (*first == value)
                break;
        return first;
    }
    

    That’s it. The change is so minor, you might even have a hard time spotting it!

    So, which C++98 algorithms can be made to work with Iterables instead of Ranges? Nearly all of them, it turns out. In fact, it’s easier to list the ones that don’t work with Iterables. They are:

    • copy_backward
    • The heap algorithms (push_heap, pop_heap, make_heap, sort_heap)
    • inplace_merge
    • nth_element
    • partial_sort and partial_sort_copy
    • next_permutation and prev_permutation
    • random_shuffle
    • reverse and reverse_copy
    • sort and stable_sort
    • stable_partition

    For the 50 or so others, getting them to work with Iterables is mostly a mechanical source code transformation. By defining the Iterable concept such that Range refines it, any algorithm implemented in terms of Iterable automatically works with Ranges, which lets us reuse code. And that’s super important. There’s too much code written for iterators to think about picking an incompatible abstraction now.

    The Proof is in the Perf

    But what do we gain? Let’s revisit our old friend, the C-style null-terminated string. In a previous post, I defined a c_string_range class and found that iterating through the characters generated very bad code. Let’s try again, this time using my range_facade helper to build an Iterable instead of a Range. The code looks like this:

    using namespace ranges;
    struct c_string_iterable
      : range_facade<c_string_iterable>
    {
    private:
        friend range_core_access;
        char const *sz_;
        char const & current() const { return *sz_; }
        void next() { ++sz_; }
        bool done() const { return *sz_ == 0; }
        bool equal(c_string_iterable const &that) const
        { return sz_ == that.sz_; }
    public:
        c_string_iterable(char const *sz)
            : sz_(sz) {}
    };
    

    The first thing we notice is that this code is a lot simpler than the old c_string_range class. The range_facade helper does all the heavy lifting here. The iterator and the sentinel are all implemented in terms of the primitives shown. Gone is the awkward and complicated equality comparison. But how does it perform? To test it, I generated the optimized assembly for the following two functions, one which used the old c_string_range class, and one that uses the new c_string_iterable:

    // Range-based
    int range_strlen(
        c_string_range::iterator begin,
        c_string_range::iterator end)
    {
        int i = 0;
        for(; begin != end; ++begin)
            ++i;
        return i;
    }
    
    // Iterable-based
    int iterable_strlen(
        range_iterator_t<c_string_iterable> begin,
        range_sentinel_t<c_string_iterable> end)
    {
        int i = 0;
        for(; begin != end; ++begin)
            ++i;
        return i;
    }
    

    Even if you don’t know much about assembly code, the following should speak to you:

    Range-based strlen Iterable-based strlen
        pushl    %ebp
        movl    %esp, %ebp
        pushl    %esi
        leal    8(%ebp), %ecx
        movl    12(%ebp), %esi
        xorl    %eax, %eax
        testl    %esi, %esi
        movl    8(%ebp), %edx
        jne    LBB2_4
        jmp    LBB2_1
        .align    16, 0x90
    LBB2_8:
        incl    %eax
        incl    %edx
        movl    %edx, (%ecx)
    LBB2_4:
        testl    %edx, %edx
        jne    LBB2_5
        cmpb    $0, (%esi)
        jne    LBB2_8
        jmp    LBB2_6
        .align    16, 0x90
    LBB2_5:
        cmpl    %edx, %esi
        jne    LBB2_8
        jmp    LBB2_6
        .align    16, 0x90
    LBB2_3:
        leal    1(%edx,%eax), %esi
        incl    %eax
        movl    %esi, (%ecx)
    LBB2_1:
        movl    %edx, %esi
        addl    %eax, %esi
        je    LBB2_6
        cmpb    $0, (%esi)
        jne    LBB2_3
    LBB2_6:
        popl    %esi
        popl    %ebp
        ret
            
        pushl    %ebp
        movl    %esp, %ebp
        movl    8(%ebp), %ecx
        xorl    %eax, %eax
        cmpb    $0, (%ecx)
        je    LBB1_4
        leal    8(%ebp), %edx
        .align    16, 0x90
    LBB1_2:
        cmpb    $0, 1(%ecx,%eax)
        leal    1(%eax), %eax
        jne    LBB1_2
        addl    %eax, %ecx
        movl    %ecx, (%edx)
    LBB1_4:
        popl    %ebp
        ret
            

    The code generated from the Iterable algorithm is far superior to that generated from the pair of iterators. In fact, if you check it against the assembly for the raw C-style iteration, you’ll find it’s almost identical.

    Iterators, Sentinels, and Equality

    But what does it mean to compare two objects of different types for equality? Or put in more formal terms, can the requirement that an Iterable’s iterator and sentinel satisfy the cross-type EqualityComparable concept be satisfied? I believe the answer is yes.

    Some background for the uninitiated: N3351 defines precisely when and how cross-type equality comparisons are meaningful. It’s not enough for the syntax “x==y” to be valid and yield a bool. If x and y have different types, the types of both x and y must themselves be EqualityComparable, and there must be a common type to which they can both be converted, and that type must also be EqualityComparable. Think of comparing a char with a short. It works because both char and short are EqualityComparable, and because they can both be converted to an int which is also EqualityComparable.

    Iterators are comparable, and sentinels are trivially comparable (they always compare equal). The tricky part is the common type requirement. Logically, every iterator and sentinel has a common type that can be constructed as follows: assume the existence of a new iterator type I that is a tagged union that contains either an iterator or a sentinel. When an iterator is compared to a sentinel, it behaves semantically as if both the iterator and the sentinel were first converted to two objects of type I — call them lhs and rhs — and then compared according to the following truth table:

    lhs is sentinel ? rhs is sentinel ? lhs == rhs ?
    true true true
    true false done(rhs.iter)
    false true done(lhs.iter)
    false false lhs.iter == rhs.iter

    If you’ve been following this series, the above truth table should ring a bell. It’s pretty much exactly the table we got when figuring out how c_string_range::iterator‘s equality operator should behave, and that’s no coincidence; that was a special case of this more general construction. This construction validates an intuition you might have after seeing the two classes I wrote, c_string_range and c_string_iterable. One is a pair of iterators, the other an iterator/sentinel pair, but they implement equivalent procedures for computing equality. We know they’re the same, and we feel in our guts we could build an equivalent Range out of every Iterable if we’re willing to sacrifice some performance. And now we know that’s true.

    Allowing direct comparison of iterators and sentinels lets us use the C++ type system to optimize a large category of iterations by eliminating branches from the equality comparison operator.

    Objections

    The idea of allowing begin and end iterators to have different types is not new, and it’s not mine. (In fact, many of you who have commented on the first two posts, either here or on reddit.com, have made precisely this suggestion.) I first heard about it from Dave Abrahams years ago. More recently, Dietmar Kuehl floated a similar idea on the Ranges mailing list. Sean Parent raised the following objection in a follow-up message:

    Again, I think this is putting too much on iterators. Algorithms that act with a sentinel termination or with a count are different beasts. See copy_n() and copy_sentinel()

    http://stlab.adobe.com/copy_8hpp.html

    For ranges – I certainly thing you should be able to construct a range with:

    1. a pair of iterators
    2. an iterator and a count
    3. an iterator and a sentinel value

    In which case, copy(r, out) can dispatch to the correct algorithm.

    If I’m understanding Sean correctly, he is arguing for 3 parallel range concept hierarchies: IteratorRange, CountedRange, and SentinelRange. These hierarchies would have no refinement relationships between them. The copy algorithm would have three underlying implementations, one for each concept hierarchy. There are 50 some odd algorithms that would need to be triplicated in this way. That’s a lot of code duplication.

    In fact, it’s worse than that because some algorithms are specialized to take advantage of more refined concepts. For instance, in libc++, the rotate algorithm dispatches to one of three implementations depending on whether you pass it forward, bidirectional, or random-access iterators. To accommodate Iterator, Counted, and SentinelRanges, we would need a grand total of 9 rotate algorithm implementations! I have nothing but respect for Sean Parent, but that’s madness. With the Iterable concept, Sean’s three separate hierarchies get unified under a single syntax that lets us write general algorithms while preserving performance characteristics. In other words, with Iterables, 3 implementations of rotate suffice.

    (Incidentally, the Iterable concept can neatly accommodate counted ranges. If you want to turn an iterator and a count into an Iterable, you can bundle the iterator and the count together into a new iterator type that decrements the count whenever the iterator is incremented. When comparing the iterator to the sentinel, it merely checks whether the count is zero.)

    Summary, For Now…

    At the beginning of this post I summarized some of the problems with pair-o’-iterator ranges. I showed how a new concept, Iterable, addresses the performance issues, and touched a bit on the issue of range implementation complexity. I haven’t yet covered how the Iterable concept helps with infinite ranges, or how to address the safety issue of passing an infinite range to an algorithm that can’t handle them. This post has run a bit long, so I’ll stop for now and address the other issues in the fourth and final installment. Hopefully, this has given you a few things to think about until then.

    If you want to download and play with the code, you can find it in the range-v3 repository on github. I’m happy to take suggestions and bug reports, but please don’t use this code for anything real. It’s untested and still evolving.

    Acknowledgements

    I’d like to thank Andrew Sutton for helping with the Concept Lite syntax and also for explaining the requirements of the cross-type EqualityComparable concept and generally improving and formalizing many of the ideas presented here. The article is immeasurably better for his many contributions.

    x
    x
  • Range Concepts, Part 2 of 4: Infinite Ranges

    In the last post, I tried to make delimited ranges fit into the STL and found the result unsatisfying. This time around I’ll be trying the same thing with infinite ranges and will sadly be reaching the same conclusion. But the exercise will point the way toward an uber-Range concept that will subsume delimited ranges, infinite ranges, and STL-ish pair-o’-iterator ranges.

    Infinite Ranges

    Building motivation for delimited ranges was fairly simple; we’re all familiar with the idea from null-terminated strings. The case for infinite ranges is bit harder to make. As C++ programmers, we don’t regularly bump into infinity. In other languages infinity is all in a day’s work. Haskell programmers can create an infinite list of integers as simply as typing [1..]. Does that break your brain? It shouldn’t. It’s a lazy list — the elements are generated on demand. All infinite ranges are necessarily lazy.

    What’s the use of that? Consider the take algorithm which constructs a new list from the first N elements of another list. It handles infinite lists with aplomb. Or consider what should happen when you zip an infinite list with a finite one. You end up with a finite list of element pairs. That’s a perfectly sensible thing to do.

    Supporting infinite ranges in a generic range library would be a boon, so it’s worth looking at what it does to the concepts.

    Infinite Ranges in the STL

    We might think of infinite ranges as a kind of degenerate delimited range where the delimiting predicate always returns false. When we’re trying to reach infinity, our work is never done. With that in mind, let’s implement an infinite range of integers starting at some value and ending never. It’s described below.

    struct iota_range
    {
    private:
        int i_;
    public:
        using const_iterator = struct iterator
          : boost::iterator_facade<
                iterator, int const,
                std::forward_iterator_tag
            >
        {
        private:
            bool sentinel_;
            int i_;
            friend class boost::iterator_core_access;
            friend struct iota_range;
            iterator(int i) : sentinel_(false), i_(i) {}
            bool equal(iterator that) const
            {
                return sentinel_ == that.sentinel_
                    && i_ == that.i_;
            }
            void increment() 
            {
                ++i_;
            }
            int const & dereference() const
            {
                return i_;
            }
        public:
            iterator() : sentinel_(true), i_(0) {}
        };
        constexpr explicit iota_range(int i = 0)
          : i_(i)
        {}
        iterator begin() const
        {
           return iterator{i_};
        }
        iterator end() const
        {
           return iterator{};
        }
        constexpr explicit operator bool() const
        {
           return true;
        }
    };
    

    With this range, we can do this:

    // Spew all the ints. WARNING: THIS NEVER ENDS!
    for( int i : iota_range() )
        std::cout << i << 'n';
    

    iota_range is a forward range; that is, its iterators model the ForwardIterator concept 1. They store both an integer and a Boolean signifying whether the iterator is a sentinel or not. The range’s begin iterator is not a sentinel, the end iterator is. Therefore, they will never compare equal, and we’ll count integers … forever!

    A Funny Thing Happened on the Way to Infinity

    What you’ll find when you use this range in your code is that some things will work as you expect and other things will spin off into hyperspace and never come back. Take a very simple example: std::distance. Presumably, you won’t be foolish enough to do this:

    iota_range iota;
    // Oops!
    auto dist = std::distance(iota.begin(), iota.end());
    

    What’s less clear is that you should never, ever, under any circumstance, pass this range directly or indirectly to any algorithm that does binary searching, including binary_search, lower_bound, upper_bound, and equal_range — despite the fact that iota_range is, in fact, a sorted forward range. Think about it: binary searching is a divide-and-conquer algorithm. Dividing an infinite range yields — surprise! — an infinite range. If you pass an iota_range to any of these algorithms, go get yourself a cup of coffee. You could be waiting a while.

    Performance Problems

    If you read the last blog post about delimited ranges, maybe you cringed a bit when you saw the implementation of iota_range::iterator::equal. It is our intention that an iota_range‘s iterator will never, ever finish iterating, so the termination condition should be a constant expression. Instead, we have this:

    bool equal(iterator that) const
    {
        return sentinel_ == that.sentinel_
            && i_ == that.i_;
    }
    

    That’s two runtime checks when it should be zero! As I showed last time, this can have a disastrous effect on the quality of the generated code.

    Possibly Infinite Ranges

    Infinite loops are one problem with infinite ranges, but there’s another more subtle problem, and unfortunately it already exists in the Standard Library. Take our old friend (and my favorite punching bag) std::istream_iterator. It is an input iterator, so it’s required to have an associated difference_type. In “Elements of Programming,” Alexander Stepanov (the father of the STL and of Generic Programming) says this about an Iterator’s difference type:

    DistanceType returns an integer type large enough to measure any sequence of applications of successor allowable for the type. 2

    For istream_iterator‘s, the difference_type is std::ptrdiff_t. Now, consider the following code:

    std::istream& sin = ...;
    std::istream_iterator<char> it{sin}, end;
    std::ptrdiff_t dis = std::distance(it, end);    
    

    This is perfectly reasonable and valid code. It pulls characters out of the istream, counts them, and discards them. Now, imaging sin is pulling characters from the network, and that this code runs for days, pulling billions and billions of characters off the net. What happens when a ptrdiff_t isn’t big enough to hold the result? Answer: undefined behavior. In practice, you’ll get garbage, but in principle, anything could happen.

    To me, that’s a little disconcerting. An iterator’s difference_type should be big enough to hold the distance between any two iterators. Since input streams are unbounded in principle, there is no scalar signed integer type that’s big enough. Huh. We’re forced to conclude that the validity of istream_iterator‘s increment operation is limited by the size of its difference_type, or that istream_iterator‘s difference_type is wrong. Again: Huh.

    Summary, For Now…

    Infinite ranges are useful, but they have real problems given the current definition of the STL. You might think that disallowing infinite ranges avoids the problem, but it’s more fundamental than that. In fact, some problems exist today. It’s hard to fix the difference_type overflow issue in the STL today (apart from telling people to be careful), but it’s worth considering whether a new range-based interface can help. (So as not to raise expectations, I’ll say now that this is a vexing problem that I don’t yet have a great solution to.)

    Summing up, here are the issues I’ve identified so far with STL-ish pair-o’-iterators-style ranges:

    • Delimited and infinite ranges generate poor code
    • They are forced to model weaker concepts than they might otherwise
    • Also, they’re awkward to implement
    • It’s too easy to pass an infinite range to an algorithm that can’t handle it
    • Possibly-infinite ranges can overflow their difference_type

    In the next installment, I’ll describe the conceptual foundations of my new range library that strikes at the root of these problems. Stay tuned.


    1. Actually, this is a bit of a lie. Forward iterators aren’t supposed to return references to objects inside them. Please ignore this for the sake of discussion.↩

    2. Stepanov, A; McJones, P. Elements of Programming. Addison-Wesley. 2009.↩

    x
    x
  • Range Concepts, Part 1 of 4: Delimited Ranges

    I’ve been digging into ranges recently, and I’m finding them to be more than just a pair of iterators. In a series of posts, I’ll be expanding the notion of what a range is to cover some kinds of ranges not easily or efficiently expressible within the STL today: delimited ranges and infinite ranges. This post deals with the problems of representing delimited ranges with STL iterators.

    Delimited Ranges

    When groping about for concepts, it’s essential to have some concrete examples in mind. So when I say “delimited range,” think: null-terminated C-style string. The end of the sequence is not some known position; rather, it’s an unknown position at which we expect to find some delimiter, or more generally, at which some predicate becomes true. Another example, interestingly, is an istream range. The delimiter in that case is when the istream extractor fails. And yet, the standard has std::istream_iterator, so clearly it’s not impossible to shoehorn delimited ranges into the STL. I’ll show how, and explain why I use the term “shoehorn.”

    Delimited Ranges in the STL

    To prove my “shoehorn” allegation, here is a delimited range over a C-style string with fully STL-compliant iterators:

    #include <cassert>
    #include <iostream>
    #include <boost/iterator/iterator_facade.hpp>
    
    struct c_string_range
    {
    private:
        char const *str_;
    public:
        using const_iterator = struct iterator
          : boost::iterator_facade<
                iterator
              , char const
              , std::forward_iterator_tag
            >
        {
        private:
            friend class boost::iterator_core_access;
            friend struct c_string_range;
            char const * str_;
            iterator(char const * str)
              : str_(str)
            {}
            bool equal(iterator that) const
            {
                return str_
                    ? (that.str_ == str_ ||
                         (!that.str_ && !*str_))
                    : (!that.str_ || !*that.str_);
            }
            void increment()
            {
                assert(str_ && *str_);
                ++str_;
            }
            char const& dereference() const
            {
                assert(str_ && *str_);
                return *str_;
            }
        public:
            iterator()
              : str_(nullptr)
            {}
        };
        c_string_range(char const * str)
          : str_(str)
        {
            assert(str_);
        }
        iterator begin() const
        {
            return iterator{str_};
        }
        iterator end() const
        {
            return iterator{};
        }
        explicit operator bool() const
        {
            return !!*str_;
        }
    };
    
    int main()
    {
        for(char c : c_string_range("hello world!"))
            std::cout << c;
        std::cout << 'n';
    }
    

    The code traverses the sequence of characters without first computing its end. It does it by creating a dummy end iterator — a sentinel — such that any time a real iterator is compared to it, it checks to see if the real iterator points to the null terminator. All the gross logic is there in the c_string_range::iterator::equal member function. Nobody would call this code beautiful or elegant.

    In the STL today, ranges are specified with two iterators: the begin and the end. For iterators like std::istream_iterator or c_string_range::iterator where an iterator can be a sentinel, it adds branches to the iterator equality test since you first have to determine if one or both of the iterators are sentinels. The expression a == b is evaluated according to the following truth table:

    a == end ? b == end ? a == b ?
    true true true
    true false *b == 0
    false true *a == 0
    false false &*a == &*b

    The above tests must be evaluated at runtime! There’s no way to know a priori whether an iterator is a real iterator or a dummy one. And all that checking is expensive. That’s what I mean when I say that delimited ranges can be “shoehorned” into the STL. It’s not a comfortable fit.

    The Compiler Agrees

    And when I say it’s an uncomfortable fit, that’s not just my opinion. I generated code for the following two functions:

    int c_strlen(char const *sz)
    {
        int i = 0;
        for(; *sz; ++sz)
            ++i;
        return i;
    }
    
    int range_strlen(
        c_string_range::iterator begin,
        c_string_range::iterator end)
    {
        int i = 0;
        for(; begin != end; ++begin)
            ++i;
        return i;
    }
    

    The two functions do exactly the same thing, so in theory they should generate the same code. Our Spidey-sense should be tingling though after seeing the complicated conditional logic in c_string_range::iterator::equal. Indeed, the code they generate is far from comparable:

    c_strlen range_strlen
        pushl   %ebp
        movl    %esp, %ebp
        movl    8(%ebp), %ecx
        xorl    %eax, %eax
        cmpb    $0, (%ecx)
        je  LBB1_3
        xorl    %eax, %eax
        .align  16, 0x90
    LBB1_2:
        cmpb    $0, 1(%ecx,%eax)
        leal    1(%eax), %eax
        jne LBB1_2
    LBB1_3:
        popl    %ebp
        ret
            
        pushl   %ebp
        movl    %esp, %ebp
        pushl   %esi
        leal    8(%ebp), %ecx
        movl    12(%ebp), %esi
        xorl    %eax, %eax
        testl   %esi, %esi
        movl    8(%ebp), %edx
        jne LBB2_4
        jmp LBB2_1
        .align  16, 0x90
    LBB2_8:
        incl    %eax
        incl    %edx
        movl    %edx, (%ecx)
    LBB2_4:
        testl   %edx, %edx
        jne LBB2_5
        cmpb    $0, (%esi)
        jne LBB2_8
        jmp LBB2_6
        .align  16, 0x90
    LBB2_5:
        cmpl    %edx, %esi
        jne LBB2_8
        jmp LBB2_6
        .align  16, 0x90
    LBB2_3:
        leal    1(%edx,%eax), %esi
        incl    %eax
        movl    %esi, (%ecx)
    LBB2_1:
        movl    %edx, %esi
        addl    %eax, %esi
        je  LBB2_6
        cmpb    $0, (%esi)
        jne LBB2_3
    LBB2_6:
        popl    %esi
        popl    %ebp
        ret
            

    Oh my! Look at all those tests and branches! The above code was generated with clang 3.4 with -O3 -DNDEBUG. I should add that in practice, the compiler can often generate better code for range_strlen. If the compiler can infer statically that end is in fact a sentinel, and if the definition of range_strlen is available for inlining, then the compiler will generate better code. Near-optimal, in fact. But those are some big “If”s.

    Besides, people generally don’t contort themselves by writing the c_string_range class when dealing with delimited strings. They call strlen and then some algorithm, traversing the range twice instead of once. But consider the case of the istream range. You can’t do the same trick with an input range because merely finding the end iterator consumes the range! Now we see why std::istream_iterator has a dummy sentinel. There’s simply no other way.

    And as a final note, observe that c_string_range::iterator is a forward iterator, despite the fact that the raw char const* it wraps is random-access. That’s because the sentinel cannot be decremented. The range’s iterator can only be as powerful as its sentinel, which is pretty darn weak.

    So What?

    So we can’t efficiently use STL algorithms on C-style strings. Big deal, right? Actually, it is. It means that pretty much all generic string algorithms cannot be used on C-style strings. Look at all the juicy string algorithms in Boost.String_algo. The docs say this about the string types it supports:

    “Definition: A string is a range of characters accessible in sequential ordered fashion. […] First requirement of string-type is that it must accessible using Boost.Range. This facility allows to access the elements inside the string in a uniform iterator-based fashion.”

    No love for C-style strings from Boost.String_algo. And by the way, what do you think happens when you call std::regex_search with a C-style string? It first calls strlen! So even if your string is megabytes long and the match is at the very front, you first have to traverse the entire string just so that you know where the end is. Which is all totally pointless.

    “You shouldn’t be using C-style strings anyway,” you say. But the problem is bigger than C-style string. All delimited ranges have this problem. Just within the standard library, there are istream_iterator, istreambuf_iterator, regex_iterator, and regex_token_iterator, all of which have dummy sentinels, all of which have been shoehorned in like I’ve shown above. I’m sure you can think of others.

    Dietmar Kuehl alerted me to another interesting case. Have you ever wanted to call a generic algorithm but couldn’t because you wanted to break out of the loop early under some condition? Imagine that you could build a delimited range with that predicate and the end iterator. Now you can pass that range to an algorithm and it would stop either when the predicate becomes true or when you reach the end of the sequence. Voila! Standard algorithms just got a lot more useful. But this iterator type would have to be shoehorned in like the others, and you wouldn’t be able to call any algorithm that required more than forward iterators since you can’t decrement the sentinel.

    Conclusion, For Now…

    What’s my point? My point is this: the pair-of-iterators range abstraction that we are familiar with and that was designed to have low abstraction cost has real abstraction cost that cannot be avoided for delimited ranges. It also forces delimited ranges to model weaker concepts than they might otherwise, and makes their implementation awkward. What’s the solution? I do have a concrete suggestion, but we’re not there yet. First I want to talk about infinite ranges, and then we’ll see how delimited, infinite and pair-o’-iterators ranges can all be subsumed into a larger Range concept. Tune in next time…

    Acknowledgements

    I’d like to Dietmar Kuehl and Andrew Sutton for helping me formulate my range ideas and for reviewing this article.

    x
    x