Conduit
A header-only C++ library that leverages the Coroutine TS to bring lazy sequences to C++ — infinite sequences, sequence transformations, and zero-cost abstractions.
Conduit is a header-only C++ library built on the Coroutine TS that introduces lazy sequences to C++. It enables concise, composable, and efficient lazy computation — including infinite sequences — with zero runtime overhead thanks to compiler optimization.
What is a Lazy Sequence?
A lazy sequence computes elements only when they are requested, rather than upfront. This enables:
- Infinite sequences — represent sequences that could never fit in a vector
- Efficient pipelines — only compute what you actually consume
- Separation of concerns — decouple the sequence definition from its consumption
Basic Usage
Define a sequence using the seq<T> return type and co_yield:
auto squares = []() -> seq<int> {
int x = 0;
while (true) {
co_yield x * x;
++x;
}
};Iterate over it like any standard range:
for (auto x : squares() >> take(10)) {
std::cout << x << "\n";
}Collect into a vector:
std::vector<int> v = range() >> take(5) >> toVector();
// v = { 0, 1, 2, 3, 4 }Sequence Transformations
Conduit provides a rich set of combinators using the >> operator:
// Sum of the first 10 squares
auto total = squares() >> take(10) >> sum();
// Fibonacci sequence
auto fibonacci = []() -> seq<int> {
int a = 0, b = 1;
while (true) {
co_yield a;
tie(a, b) = tuple{a + b, a};
}
};
// Dice rolls with cumulative sum
auto rolls = randoms(0)
>> map([](auto x) { return ceil(x * 6); })
>> scan(0, [](auto x, auto y) { return x + y; })
>> take(6);Zero-Cost Abstractions
Clang optimizes away the coroutine machinery entirely. The following program:
auto items = fibonacci() >> drop(40) >> take(50);
unsigned long long result = 0;
for (auto x : items) result += x;
return result;Compiles down to a single mov instruction — the result is computed at compile time.
Installation
Conduit is a header-only library. Clone the repository and add the include/ directory to your include path:
git clone https://github.com/LoopPerfect/conduitYou need a C++ compiler with Coroutine TS support (Clang with -fcoroutines-ts).
Related
- Introducing Conduit: Lazy Sequences for C++ — A tour of Conduit with square numbers, transformations, and the Fibonacci benchmark.
- C++ Coroutine TS — It's About Inversion of Control — The deeper motivation: separating concerns with lazy sequences.