Skip to content

Instantly share code, notes, and snippets.

@susisu
Last active August 5, 2020 18:14
Show Gist options
  • Save susisu/96c0df8ae2d94595b954 to your computer and use it in GitHub Desktop.
Save susisu/96c0df8ae2d94595b954 to your computer and use it in GitHub Desktop.
var Monoid = {
mempty: function (m) { return m.__Monoid__.mempty; },
mappend: function (m) { return m.__Monoid__.mappend; },
mconcat: function (m) {
return function (array) {
return array.reduceRight(
function (a, b) { return Monoid.mappend(m)(b, a); },
Monoid.mempty(m)
);
};
}
}
String.__Monoid__ = {
mempty: "",
mappend: function (a, b) { return a + b; }
};
Number.__Monoid__ = {
mempty: 0,
mappend: function (a, b) { return a + b; }
};
Array.__Monoid__ = {
mempty: [],
mappend: function (a, b) { return a.concat(b); }
};
Monoid.mconcat(String)(["foo", "bar", "baz"]); // => "foobarbaz"
Monoid.mconcat(Number)([1, 2, 3]); // => 6
Monoid.mconcat(Array)([["a", "b"], ["c"], ["d", "e", "f"]]); // => ["a", "b", "c", "d", "e", "f"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment