Created
March 18, 2014 08:10
-
-
Save SegFaultAX/9615583 to your computer and use it in GitHub Desktop.
Functional sets in Javascript
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
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