// C++ iteration. Based on Alexandrescu's "range" concept.
#include <iostream>
// range: generate a sequence of numbers, modeled after Python.
template<typename T>
class Range {
private: T cur, end, step;
public:
Range(const T _start, const T _end, const T _step):
cur(_start), end(_end), step(_step) {}
bool nil() const { return cur == end; }
T first() const { return cur; }
void next() { cur += step; }
typedef T elem;
};
template<typename T>
inline Range<T> range(const T _start, const T _end, const T _step) {
return Range<T>(_start, _end, _step);
}
template<typename T>
inline Range<T> range(const T _start, const T _end) {
return range(_start, _end, T(1));
}
template<typename T>
inline Range<T> range(const T _end) {
return range(T(0), _end);
}
// map: transform each element of a sequence with a function
template<typename I, typename F>
class Map {
private:
I iter;
F func;
public:
Map(I _iter, F _func): iter(_iter), func(_func) {}
bool nil() const { return iter.nil(); }
typedef typename F::return_type elem;
elem first() const { return func(iter.first()); }
void next() { iter.next(); }
};
template<typename I, typename F>
inline Map<I, F> map(const I _iter, const F _func)
{
return Map<I, F>(_iter, _func);
}
// for_each: call a function for each item of a sequence
template<typename I, typename F>
void for_each(I seq, F f)
{
for (; !seq.nil(); seq.next()) f(seq.first());
}
// Example application logic: IntPrinter and Squarer
class IntPrinter {
public:
void operator()(int x) const
{
std::cout << x << " ";
}
};
class Squarer {
public:
typedef int return_type;
return_type operator()(int x) const
{
return x * x;
}
};
int main ()
{
for_each(map(range(10), Squarer()), IntPrinter());
std::cout << "\n";
return 0;
}
--
To unsubscribe: http://lists.canonical.org/mailman/listinfo/kragen-hacks