Instantly share code, notes, and snippets.

# splinterofchaos/pure-test.cpp Created Jul 18, 2012

Pure.h use-case
 #include #include #include #include #include #include #include using namespace std; using namespace placeholders; #define RNG(seq) seq.begin(), seq.end() void print( const char* const msg, const vector& v ) { cout << msg << "\n"; copy( RNG(v), ostream_iterator(cout, " ") ); cout << "\n\n"; } template< typename Printable > void print_val( const char* const msg, const Printable& p ) { cout << msg << '\n' << p << "\n\n"; } bool even( int x ) { return x % 2 == 0; } vector qsort( vector v ) { const int pivot = v.front(); return ordered(v) ? v : concat ( qsort( filter([=](int x){return x< pivot;}, v) ), qsort( filter([=](int x){return x==pivot;}, v) ), qsort( filter([=](int x){return x> pivot;}, v) ) ); } int main() { vector a(10); iota( RNG(a), 1 ); print( "a = [ x | x <- [1..10] ]", a ); vector fib(10,1); transform( fib.begin(), fib.end() - 2, // src 1 fib.begin() + 1, // src 2 fib.begin() + 2, // dest plus() ); print( "fib 0 = 1\nfib 1 = 1\nfib x = fib (x-1) fib (x-2)", fib ); vector b; transform( RNG(a), back_inserter(b), bind( plus(), _1, 4) ); print( "map (+4) a", b ); vector c; auto end = copy_if( RNG(a), back_inserter(c), even ); print( "filter even a", c ); bool allof = all_of( RNG(c), even ); print_val("all even (filter even a)", allof? "t" : "f" ); auto x = accumulate( RNG(a), 2, multiplies() ); print_val( "foldl (*) 2 a", x ); vector outOfOrder = { 2, 5, 3, 1 }; print_val( "maximum [2,5,3,1]", *max_element(RNG(outOfOrder)) ); srand( time(0) ); vector randoms(10); generate( RNG(randoms), &rand ); print( "g <- getStdGen\n" "qsort \$ take 10 (randoms g)::[Int]", qsort(randoms) ); // Currying. auto prnt = bind( print, "...", _1 ); prnt(a); prnt(b); }