Skip to content

Instantly share code, notes, and snippets.

@SegFaultAX
Created March 18, 2014 08:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SegFaultAX/9615583 to your computer and use it in GitHub Desktop.
Save SegFaultAX/9615583 to your computer and use it in GitHub Desktop.
Functional sets in Javascript
function empty() {
return function() {
return false;
};
}
function singleton(e0) {
return function(e) {
return e0 === e;
};
}
function contains(s, e) {
return s(e);
}
function union(s1, s2) {
return function(e) {
return contains(s1, e) || contains(s2, e);
};
}
function intersect(s1, s2) {
return function(e) {
return contains(s1, e) && contains(s2, e);
};
}
function difference(s1, s2) {
return function(e) {
return contains(s1, e) && !contains(s2, e);
};
}
function filter(s, pred) {
return function(e) {
return pred(e) && contains(s, e);
};
}
function add(s, e) {
return union(s, singleton(e));
}
function remove(s, e) {
return difference(s, singleton(e));
}
function toSet(l) {
var acc = empty();
for (var i = 0; i < l.length; i++) {
acc = union(acc, singleton(l[i]));
}
return acc;
}
function setOf() {
var args = Array.prototype.slice.call(arguments);
return toSet(args);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment