Jonathan Boccara's blog

New Pipes + a Video Tutorial to Make More Pipes

Published November 8, 2019 - 0 Comments

The pipes library got 4 more pipes: take, take_while, drop and drop_while. We’re going to see what those new pipes do, and then a video of how I implemented them that can serve as a guide to implement more.

take and take_while

The take and take_while pipes are equivalent to their range adaptor counterparts: they let through the first values they receive pass, and ignore the values after a certain point.

take and take_while have different ways of determining that point. take lets through a fixed number of values:

auto const input = std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto result = std::vector<int>{};

input >>= pipes::take(6)
      >>= pipes::push_back(result);
      
// result contains {1, 2, 3, 4, 5, 6}

And take_while lets values through until one doesn’t satisfy a predicate:

auto const input = std::vector<int>{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto result = std::vector<int>{};

input >>= pipes::take_while([](int i){ return i != 7; })
      >>= pipes::push_back(result);

// result contains {1, 2, 3, 4, 5, 6}

drop and drop_while

drop is the complementary operation of take: it starts letting values through after a certain point. drop determines that point as a number of incoming values:

auto const input = std::vector<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto result = std::vector<int>{};

input >>= pipes::drop(6)
      >>= pipes::push_back(result);

// result contains { 7, 8, 9, 10 }

And drop_while starts letting values through when one of them satisfies a predicate:

auto const input = std::vector<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto result = std::vector<int>{};

input >>= pipes::drop_while([](int i){ return i != 7; })
      >>= pipes::push_back(result);

// result contains { 7, 8, 9, 10 }

A video tutorial

Implementing those pipes is pretty straightforward, and you can see how to do it in this video:

This video shows how to implement drop and drop_while, which are good examples of how to implement a pipe. In the video, we write the unit tests and then the code for the two pipes, while commenting on the library’s design.

If you’d like to submit a new pipe to the pipes library, this video can help guide you in its implementation.

You will also like

Don't want to miss out ? Follow:   twitterlinkedinrss
Share this post!Facebooktwitterlinkedin