Last active
August 29, 2015 14:19
-
-
Save TGOlson/31c17593bbd736df0339 to your computer and use it in GitHub Desktop.
Or operator as a monoid
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
'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