Skip to content

Instantly share code, notes, and snippets.

@TGOlson
Created April 25, 2015 19:35
Show Gist options
  • Select an option

  • Save TGOlson/08b82d05816cbbe4d0d9 to your computer and use it in GitHub Desktop.

Select an option

Save TGOlson/08b82d05816cbbe4d0d9 to your computer and use it in GitHub Desktop.
All as a monoid
'use strict';
// All (||) operator as a monoid
function All(v) {
return {
value: v
};
}
function binary(v1, v2) {
return v1 && v2;
}
function empty() {
return All(true);
}
function append(m1, m2) {
return All(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(), All(true));
assertSameValue(appendEmptyLeft, All(true));
var appendEmptyRight = append(All(false), empty());
assertSameValue(appendEmptyRight, All(false));
// `append` must be associative
var generalAppend = append(All(false), All(true));
assertSameValue(
append(generalAppend, All(false)),
append(All(false), generalAppend)
);
// `concat` can take a list of monoid values and reduce them to a single value
assertSameValue(
concat([All(true), All(true), All(true)]),
All(true)
);
assertSameValue(
concat([All(true), All(true), All(false)]),
All(false)
);
function all(bools) {
return concat(bools.map(All)).value;
}
console.log(all([true, true, true]));
console.log(all([true, false, true]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment