码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-06-29 15:05:19      阅读:52      评论:0      收藏:0      [点我收藏+]

标签:ret   cannot   hat   pre   ESS   tor   hold   ike   ted   

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

标签:ret   cannot   hat   pre   ESS   tor   hold   ike   ted   

原文地址:https://www.cnblogs.com/Answer1215/p/13207962.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!