Boost logo

Boost :

Subject: [boost] Interest in a list comprehension library?
From: Brent Spillner (spillner_at_[hidden])
Date: 2010-12-19 13:40:42

I uploaded sample code to the Vault (in the "Miscellaneous/"
directory) that provides a concise notation for list comprehensions.
The comprehensions are evaluated lazily and can be used to populate a
std::list, vector, or deque, appended to the same, inserted after a
given iterator, or interpreted as a boost::range, including
compatibility with BOOST_FOREACH. Containers, iterator-defined
ranges, or nullary function objects can be used as generators, and
arbitrary function objects can be used to specify filter conditions.

For example, the Pythagorean Triples example from can be coded as

std::vector< boost::tuple<int,int,int> > triples =_(x, y, z)[x <<=
range(1, n), y <<= range(x, n), z <<= range(y, n), x*x + y*y == z*z];

, and the (toy) prime number generator at can be
implemented as

  std::vector<int> nonprimes = _(j)[i <<= range(2, sqrt_max), j <<=
range(2 * i, sqrt_max * sqrt_max, i)];

  boost::function<std::vector<int>::const_iterator ()> is_composite
       = bind(std::find<std::vector<int>::const_iterator, int>,
nonprimes.begin(), nonprimes.end(), ref(p));

  BOOST_FOREACH(int x, (_(p)[p <<= range(2, sqrt_max * sqrt_max),
call(is_composite) == nonprimes.end()])) { std::cout << x <<
std::endl; }

(Note the use of call() to represent delayed invocation, and the extra
() around the comprehension when used with BOOST_FOREACH.)

I've tested this so far with GCC 4.4.4, GCC 4.5.2, and Clang 2.9,
using Boost 1.42 and 1.45, and with and without -std=c++0x. Reports
of success/failure with other environments are most welcome. The code
is still in a prototype stage, so I'm more than happy to take design
suggestions and would love to hear about use cases I've overlooked.
If there's sufficient interest I will work on getting it to production
quality and writing some real documentation. I apologize in advance
for wasting everybody's time if something like this already exists in
Phoenix; I'm not too familiar with it but I skimmed the docs and
didn't see anything.


Boost list run by bdawes at, gregod at, cpdaniel at, john at