[Functional Programming] Function modelling -- 5. Endo Monoid

Endo:

It takes a type as string and output is the same type. It's concat methods works like composion. All the transform functions on the same input.

const { List } = require("immutable-ext");

const toUpper = s => s.toUpperCase();
const exclaim = s => `${s}!`;

// Endo functor
// a -> a
// string -> string
const Endo = run => ({
  run,
  concat(otherM) {
    return Endo(x => run(otherM.run(x)));
  }
});
Endo.empty = () => Endo(x => x);

const res = List([toUpper, exclaim])
  .foldMap(Endo, Endo.empty())
  .run("hello"); // HELLO!
原文地址:https://www.cnblogs.com/Answer1215/p/12499023.html