Skip to content

Instantly share code, notes, and snippets.

@okaram
Created October 4, 2012 14:18
Show Gist options
  • Save okaram/3833791 to your computer and use it in GitHub Desktop.
Save okaram/3833791 to your computer and use it in GitHub Desktop.
Functional sets in C++
typedef std::function<bool(int)> Set;
typedef std::function<bool(int)> Predicate;
Set singletonSet(int val) {
return [=](int x){return x==val;} ;
}
Set set_union(Set s1, Set s2)
{
return [=](int x){return contains(s1,x) || contains(s2,x);};
}
Set set_intersection(Set s1, Set s2)
{
return [=](int x){return contains(s1,x) && contains(s2,x);};
}
void demo_intersection(void)
{
Set s1=singletonSet(1);
Set s2=singletonSet(2);
Set s3=singletonSet(3);
Set all=set_union(s1,set_union(s2,s3));
Set s1b=set_intersection(all,s1); // back to s1, since it is the intersection of all=(s1 U s2 U s3)
Set empty=set_intersection(s1,s2); // empty set ! why ?
cout << contains(s1b,1) << endl; // what would this print and why?
}
void demo_union(void)
{
Set s1=singletonSet(1);
Set s2=singletonSet(2);
Set s3=singletonSet(3);
Set un=set_union(s1,s2);
Set all=set_union(s1,set_union(s2,s3));
cout << contains(s1,2) << endl; // this should print 0 (meaning false :)
cout << contains(s2,2) << endl; // this should print 1 (meaning true :)
cout << contains(all,3) << endl; // this should print 1 (meaning true :)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment