Created
October 4, 2012 14:18
-
-
Save okaram/3833791 to your computer and use it in GitHub Desktop.
Functional sets in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typedef std::function<bool(int)> Set; | |
typedef std::function<bool(int)> Predicate; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Set singletonSet(int val) { | |
return [=](int x){return x==val;} ; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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);}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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