[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!

 

posted @ 2020-03-15 18:10  Zhentiw  阅读(149)  评论(0)    收藏  举报