Last active
August 29, 2015 14:19
-
-
Save TGOlson/5fab91d07fda2cb9bdd6 to your computer and use it in GitHub Desktop.
Monoid factory
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'; | |
| var R = require('ramda'); | |
| var extract = R.invoke('extract', []); | |
| var makeMonoid = R.curry(function(identity, binary, v) { | |
| // test monoid identity and binary here | |
| var thisMonoid = makeMonoid(identity, binary); | |
| var curriedBinary = R.curry(binary); | |
| return { | |
| extract : R.always(v), | |
| empty : R.partial(thisMonoid, identity), | |
| append : R.compose(thisMonoid, curriedBinary(v), extract), | |
| }; | |
| }); | |
| function Monoid(props) { | |
| return makeMonoid(props.identity, props.binary); | |
| } | |
| function empty(m) { | |
| return m.empty ? m.empty() : m().empty(); | |
| } | |
| function append(m1, m2) { | |
| return m1.append(m2); | |
| } | |
| function concat(ms) { | |
| return R.reduce(append, empty(R.head(ms)), ms); | |
| } | |
| var applyWith = R.curry(function(m, vs) { | |
| return extract(concat(R.map(m, vs))); | |
| }); | |
| module.exports = { | |
| Monoid : Monoid, | |
| empty : empty, | |
| append : append, | |
| concat : concat, | |
| extract : extract, | |
| applyWith : applyWith | |
| }; |
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'; | |
| var M = require('./monoid'); | |
| var Any = M.Monoid({ | |
| identity: false, | |
| binary: function (v1, v2) { | |
| return v1 || v2; | |
| } | |
| }); | |
| var Product = M.Monoid({ | |
| identity: 1, | |
| binary: function (v1, v2) { | |
| return v1 * v2; | |
| } | |
| }); | |
| // console.log(append(empty(Any), Any(true)).value); | |
| // | |
| // console.log(append(Any(false), Any.empty()).value); | |
| // | |
| // console.log(append(Any(false), Any(true)).value); | |
| // | |
| // console.log(append(Any(false), Any(false)).value); | |
| // | |
| console.log(M.concat([Any(false), Any(false), Any(true)]).extract()); | |
| console.log(M.concat([Any(false), Any(false), Any(false)]).extract()); | |
| var any = M.applyWith(Any); | |
| console.log(any([false, false, true])); | |
| console.log(any([false, false, false])); | |
| console.log(M.applyWith(Product, [1, 3, 5, 8, 10])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment