public
Created

Pure.h use-case

  • Download Gist
pure-test.cpp
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
 
#include <functional>
#include <algorithm>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iterator>
 
using namespace std;
using namespace placeholders;
 
#define RNG(seq) seq.begin(), seq.end()
 
void print( const char* const msg, const vector<int>& v )
{
cout << msg << "\n";
copy( RNG(v), ostream_iterator<int>(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<int> qsort( vector<int> 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<int> a(10);
 
iota( RNG(a), 1 );
print( "a = [ x | x <- [1..10] ]", a );
 
vector<int> fib(10,1);
transform( fib.begin(), fib.end() - 2, // src 1
fib.begin() + 1, // src 2
fib.begin() + 2, // dest
plus<int>() );
print( "fib 0 = 1\nfib 1 = 1\nfib x = fib (x-1) fib (x-2)", fib );
 
vector<int> b;
transform( RNG(a), back_inserter(b), bind( plus<int>(), _1, 4) );
print( "map (+4) a", b );
 
vector<int> 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<int>() );
print_val( "foldl (*) 2 a", x );
 
vector<int> outOfOrder = { 2, 5, 3, 1 };
print_val( "maximum [2,5,3,1]", *max_element(RNG(outOfOrder)) );
 
srand( time(0) );
vector<int> 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);
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.