[Functional Programming] Function modelling -- 8. Compose Functors

Posted answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Functional Programming] Function modelling -- 8. Compose Functors相关的知识,希望对你有一定的参考价值。

Path: Compose Functors -> Monad Transformers -> Free Monad

 

Compose Functors:

Let‘s say we have a Task holding a Either. And we want simply apply a .map() function to transform the value inside TaskEither.

Like this:

const TaskEither = Compose(Task, Either);

TaskEither.of(2)
  .map((two) => two + 1)
  .extract()
  .fork(console.error, (either) => either.fold(console.log, console.log));

 

So how to make TaskEither composion?

const Task = require("data.task");
const Either = require("data.either");

const Compose = (F, G) => {
  const M = (fg) => ({
    extract: () => fg,
    map: (f) => M(fg.map((g) => g.map(f))),
  });
  M.of = (x) => M(F.of(G.of(x)));
  return M;
};

const TaskEither = Compose(Task, Either);

TaskEither.of(2)
  .map((two) => two + 1)
  .extract()
  .fork(console.error, (either) => either.fold(console.log, console.log));

Compose Functors can provide a way to map into nested Functors. But it cannot do chain.

So it is useful in one way, but useless in another. 

Not commonly used.

 

In next post, we will have a look Monads Transfomers to solve the problem that we cannot do chain in compose functors.

以上是关于[Functional Programming] Function modelling -- 8. Compose Functors的主要内容,如果未能解决你的问题,请参考以下文章

[Functional Programming ADT] Debug a Functional JavaScript composeK Flow

Functional programming

Functional Programming.

[Functional Programming] Monad

Functional programming-函数式编程

python learning Functional Programming.py