Created
April 25, 2015 19:35
-
-
Save TGOlson/08b82d05816cbbe4d0d9 to your computer and use it in GitHub Desktop.
All as a monoid
This file contains hidden or 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'; | |
| // 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