We see three varied examples of where natural transformations come in handy.

Let's mark the law here for Natural Transformations:

nt(F).map(f) === nf(F.map(f))

Then let's see why we might need to apply Natural Transformations:

1. Natural Transformations can improve the code proformance

For example, we have an array of numbers, we want to get larger number, apply a doulbe function, then only get first element out of the array.

const first = xs => fromNullable(xs[]);
const largeNumbers = xs => xs.filter(x => x > );
const doulbe = x => x * ; // We first run though the whole array to doulbe the number
// Then apply first to either transform -> Proformance cost
// Since nt(F).map(f) === nt(F.map(f))
const transform1 = xs => first(largeNumbers(xs).map(doulbe));
const app = xs => transform1(xs);
console.log(app([,,,])); // Either { value: 800 }

Imporved one should be get only first of larger number, then apply transform:

const first = xs => fromNullable(xs[]);
const largeNumbers = xs => xs.filter(x => x > );
const doulbe = x => x * ; // Now we get first of array and transform to either, then apply our doulbe function
const transform2 = xs => first(largeNumbers(xs)).map(doulbe);
const app = xs => transform2(xs);
console.log(app([,,,])); // Either { value: 800 }

2. Solve different nested Functors:

const fake = id =>
({id, name: 'user1', best_friend_id: id + });
// Db :: find :: id -> Task(Either)
const Db = ({
find: id => new Task((rej, res) => {
res(id > ? Right(fake(id)): Left('not found'))
})
});

For example, the code above, we have a Db.find function, which return Task(Either(User)). It would be much easier for us to work with the same Functor type, instead of multi functors. we can think about change

// Either -> Task
const eitherToTask = e =>
e.fold(Task.rejected, Task.of);

With this tool, let's see how it solve us problem:

Db.find() // Task(Right(User))

Now we chain 'eitherToTask':

Db.find() // Task(Right(User))
.chain(eitherToTask) // // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)

So after run though 'eitherToTask' we change 'Right to Task' we got 'Task(Task(User)), then the outmost 'chain' will remove 'Task(User)'

Now if we want to find User's best friend id:

Db.find() // Task(Right(User))
.chain(eitherToTask) // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)
.chain(user => Db.find(user.best_friend_id)) // Task(User) --Db.find--> Task(Task(Right(User))) --chain--> Task(Right(User))

We know that 'Db.find(user.best_friend_id)' returns 'Task(Right(User))', inner most function call return 'Task(Task(Right(User)))', after outter most 'chain', we got 'Task(Right(User))'.

Now we can apply the trick again:

Db.find() // Task(Right(User))
.chain(eitherToTask) // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)
.chain(user => Db.find(user.best_friend_id)) // Task(User) --Db.find--> Task(Task(Right(User))) --chain--> Task(Right(User))
.chain(eitherToTask) // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)

We only got 'Task(User)' in the end, ready to be forked!

Db.find() // Task(Right(User))
.chain(eitherToTask) // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)
.chain(user => Db.find(user.best_friend_id)) // Task(User) --Db.find--> Task(Task(Right(User))) --chain--> Task(Right(User))
.chain(eitherToTask) // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)
.fork(console.error, console.log); // { id: 5, name: 'user1', best_friend_id: 6 }

--

const Either = require('data.either');
const Task = require('data.task');
const {List, Map} = require('immutable-ext');
const {Right, Left, fromNullable} = Either; const log = console.log; // F a -> G a
// nt(F).map(f) === nt(F.map(f)) //////Exp1/////
const res = List(['Hello', 'wolrd']).chain(x => x.split(''));
console.log(res.toJS()); // [ 'H', 'e', 'l', 'l', 'o', 'w', 'o', 'l', 'r', 'd' ] //////Exp2/////
const first = xs => fromNullable(xs[]);
const largeNumbers = xs => xs.filter(x => x > );
const doulbe = x => x * ; // We first run though the whole array to doulbe the number
// Then apply first to either transform -> Proformance cost
// Since nt(F).map(f) === nt(F.map(f))
const transform1 = xs => first(largeNumbers(xs).map(doulbe));
// Now we get first of array and transform to either, then apply our doulbe function
const transform2 = xs => first(largeNumbers(xs)).map(doulbe);
const app = xs => transform2(xs);
console.log(app([,,,])); // Either { value: 800 } //////Exp3/////const fake = id =>
({id, name: 'user1', best_friend_id: id + });
// Db :: find :: id -> Task(Either)
const Db = ({
find: id => new Task((rej, res) => {
res(id > ? Right(fake(id)): Left('not found'))
})
}); const eitherToTask = e =>
e.fold(Task.rejected, Task.of); Db.find() // Task(Right(User))
.chain(eitherToTask) // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)
.chain(user => Db.find(user.best_friend_id)) // Task(User) --Db.find--> Task(Task(Right(User))) --chain--> Task(Right(User))
.chain(eitherToTask) // Task(Right(User)) --EtT--> Task(Task(User)) --chain--> Task(User)
.fork(console.error, console.log); // { id: 5, name: 'user1', best_friend_id: 6 }

[Compose] 21. Apply Natural Transformations in everyday work的更多相关文章

  1. [Compose] 20. Principled type conversions with Natural Transformations

    We learn what a natural transformation is and see the laws it must obey. We will see how a natural t ...

  2. [Compose] 16. Apply multiple functors as arguments to a function (Applicatives)

    We find a couple of DOM nodes that may or may not exist and run a calculation on the page height usi ...

  3. JDK8新特性 -- Function接口: apply,andThen,compose

    1 Function<T, R>中的T, R表示接口输入.输出的数据类型. R apply(T t) apply: .例子:func是定义好的Function接口类型的变量,他的输入.输出 ...

  4. [转]Neural Networks, Manifolds, and Topology

    colah's blog Blog About Contact Neural Networks, Manifolds, and Topology Posted on April 6, 2014 top ...

  5. 壁虎书2 End-to-End Machine Learning Project

    the main steps: 1. look at the big picture 2. get the data 3. discover and visualize the data to gai ...

  6. 2020你还不会Java8新特性?

    Java8(1)新特性介绍及Lambda表达式 前言: 跟大娃一块看,把原来的电脑拿出来放中间看视频用 --- 以后会有的课程 难度 深入Java 8 难度1 并发与netty 难度3 JVM 难度4 ...

  7. [转载] 首席工程师揭秘:LinkedIn大数据后台是如何运作的?(一)

    本文作者:Jay Kreps,linkedin公司首席工程师:文章来自于他在linkedin上的分享:原文标题:The Log: What every software engineer should ...

  8. [Javascript] Functor law

    Functor laws: 1. Identity: map(id) == id 2. Composition: compose(map(f), map(g)) == map(compose(f,g) ...

  9. Category Theory: 01 One Structured Family of Structures

    Category Theory: 01 One Structured Family of Structures 这次看来要放弃了.看了大概三分之一.似乎不能够让注意力集中了.先更新吧. 群的定义 \( ...

随机推荐

  1. VS20xx IDE开发应用时_拷贝VS环境的库文件DLL到目标设备上运行的操作步骤

    问题场景: 当用VSIDE开发完一个项目,在部署到目标环境中时,配置文件OK,但是报错需要调试 <1>Deploying Visual C++ library DLLs as shared ...

  2. Actions类的一些主要方法

    下面列举一下Actions类的一些主要方法 *  keyDown.模拟按键按下 *  keyUp.模拟按键弹起 *  click *  sendKeys *  doubleClick.鼠标左键双击 * ...

  3. C#之delegate

    delegate 委托的使用: 封装一个方法,该方法只有一个参数并且不返回值. using System; using System.Windows.Forms; delegate void Disp ...

  4. 临时表VS表变量--因地制宜,合理使用

    一直以来大家对临时表与表变量的孰优孰劣争论颇多,一些技术群里的朋友甚至认为表变量几乎一无是处,比如无统计信息,不支持事务等等.但事实并非如此.这里我就临时表与表变量做个对比,对于大多数人不理解或是有歧 ...

  5. JWT【JSON Web Token】 简述

    draft: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html http://tools.ietf.org/html/ ...

  6. 无线客户端框架设计(5.1):将JSON映射为实体对象(iOS篇)

    iOS开发人员已经习惯于将JSON转换为字典或者数组来进行操作了,接下来我要做的事情,可能匪夷所思,但是,对WP和Android开发人员而言,他们更倾向于将JSON转换为实体对象进行操作. 我所设计的 ...

  7. js获取url传递参数

    <head> <meta charset="UTF-8"> <title></title> <script type=&quo ...

  8. Atitit.如何选择技术职业方向

    Atitit.如何选择技术职业方向 1. 原则是应该如下的应该从以下指标判断1 1.1. 技术的长寿性(长生命周期1 1.2. 技术的普适性(市场份额)1 1.3. **属于open体系还是封闭体系? ...

  9. paip.刮刮卡砸金蛋抽奖概率算法跟核心流程.

    paip.刮刮卡砸金蛋抽奖概率算法跟核心流程. #---抽奖算法需要满足的需求如下: 1 #---抽奖核心流程 1 #---问题???更好的算法 2 #---实际使用的扩展抽奖算法(带奖品送完判断和每 ...

  10. Maven学习总结(一副本)——Maven配置和搭建

    环境准备: JDK 1.6 Maven 3.0.4 myeclipse 8.6.1 安装 Maven 之前要求先确定你的 JDK 已经安装配置完成.Maven是 Apache 下的一个项目,目前最新版 ...