Skip to content

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Pure.h use-case
#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);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.