Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Last active August 29, 2015 14:19
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 TGOlson/31c17593bbd736df0339 to your computer and use it in GitHub Desktop.
Save TGOlson/31c17593bbd736df0339 to your computer and use it in GitHub Desktop.
Or operator as a monoid
'use strict';
// Or (||) operator as a monoid
function Or(v) {
return {
value: v
};
}
function binary(v1, v2) {
return v1 || v2;
}
function empty() {
return Or(false);
}
function append(m1, m2) {
return Or(binary(m1.value, m2.value));
}
function concat(ms) {
return ms.reduce(append, empty());
}
function assertSameValue(m1, m2) {
if(m1.value !== m2.value) {
throw new Error('Expected ' + JSON.stringify(m1) + ' to have the same value as ' + JSON.stringify(m2));
}
}
// `empty` must act as the identity with respect to `append`
var appendEmptyLeft = append(empty(), Or(true));
assertSameValue(appendEmptyLeft, Or(true));
var appendEmptyRight = append(Or(false), empty());
assertSameValue(appendEmptyRight, Or(false));
// `append` must be associative
var generalAppend = append(Or(false), Or(true));
assertSameValue(
append(generalAppend, Or(false)),
append(Or(false), generalAppend)
);
// `concat` can take a list of monoid values and reduce them to a single value
var ors = [false, false, true].map(Or);
assertSameValue(concat(ors), Or(true));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment