你们都知道JavaScript
能够做为面向对象
或者函数式
编程语言来使用,通常状况下你们理解的函数式编程
无非包括反作用
、函数组合
、柯里化
这些概念,其实并否则,若是往深了解学习会发现函数式编程
还包括很是多的高级特性,好比functor
、monad
等。国外课程网站egghead
上有个教授(名字叫Frisby)基于JavaScript
讲解的函数式编程
很是棒,主要介绍了box
、semigroup
、monoid
、functor
、applicative functor
、monad
、isomorphism
等函数式编程相关的高级主题内容。整个课程大概30节左右,本篇文章主要是对该课程的翻译与总结,有精力的强烈推荐你们观看原课程 Professor Frisby Introduces Composable Functional JavaScript 。课程最后有个小实践项目你们能够练练手,体会下这种不一样的编程方式。 这里提早声明下,本个课程里面介绍的monad
等高级特性
不见得你们都在项目中能用到,不过能够拓宽下知识面,另外也有助于学习haskell
这类纯函数式编程javascript
Box
)建立线性数据流普通函数是这样的:java
function nextCharForNumberString (str) {
const trimmed = str.trim();
const number = parseInt(trimmed);
const nextNumber = number + 1;
return String.fromCharCode(nextNumber);
}
const result = nextCharForNumberString(' 64');
console.log(result); // "A"
复制代码
若是借助Array,能够这样实现:node
const nextCharForNumberString = str =>
[str]
.map(s => s.trim())
.map(s => parseInt(s))
.map(i => i + 1)
.map(i => String.fromCharCode(i));
const result = nextCharForNumberString(' 64');
console.log(result); // ["A"]
复制代码
这里咱们把数据str
装进了一个箱子(数组),而后连续屡次调用箱子的map
方法来处理箱子内部的数据。这种实现已经能够感觉到一些奇妙之处了。再看一种基本思想相同的实现方式,只不过此次咱们不借助数组,而是本身实现箱子:git
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
toString: () => `Box(${x})`
});
const nextCharForNumberString = str =>
Box(str)
.map(s => s.trim())
.map(s => parseInt(s))
.map(i => i + 1)
.map(i => String.fromCharCode(i));
const result = nextCharForNumberString(' 64');
console.log(String(result)); // "Box(A)"
复制代码
至此咱们本身动手实现了一个箱子。连续使用map
能够组合一组操做,以建立线性的数据流。箱子中不只能够放数据,还能够放函数,别忘了函数也是一等公民:github
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
toString: () => `Box(${x})`
});
const f0 = x => x * 100; // think fo as a data
const add1 = f => x => f(x) + 1; // think add1 as a function
const add2 = f => x => f(x) + 2; // think add2 as a function
const g = Box(f0)
.map(f => add1(f))
.map(f => add2(f))
.fold(f => f);
const res = g(1);
console.log(res); // 103
复制代码
这里当你对一个函数容器调用map
时,实际上是在作函数组合。数据库
Box
重构命令式代码这里使用的Box
跟上一节同样:npm
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
toString: () => `Box(${x})`
});
复制代码
命令式moneyToFloat
:编程
const moneyToFloat = str =>
parseFloat(str.replace(/\$/g, ''));
复制代码
Box
式moneyToFloat
:json
const moneyToFloat = str =>
Box(str)
.map(s => s.replace(/\$/g, ''))
.fold(r => parseFloat(r));
复制代码
咱们这里使用Box
重构了moneyToFloat
,Box
擅长的地方就在于将嵌套表达式转成一个一个的map
,这里虽然不是很复杂,但倒是一种好的实践方式。后端
命令式percentToFloat
:
const percentToFloat = str => {
const replaced = str.replace(/\%/g, '');
const number = parseFloat(replaced);
return number * 0.01;
};
复制代码
Box
式percentToFloat
:
const percentToFloat = str =>
Box(str)
.map(str => str.replace(/\%/g, ''))
.map(replaced => parseFloat(replaced))
.fold(number => number * 0.01);
复制代码
咱们这里又使用Box
重构了percentToFloat
,显然这种实现方式的数据流更加清晰。
命令式applyDiscount
:
const applyDiscount = (price, discount) => {
const cost = moneyToFloat(price);
const savings = percentToFloat(discount);
return cost - cost * savings;
};
复制代码
重构applyDiscount
稍微麻烦点,由于该函数有两条数据流,不过咱们能够借助闭包:
Box
式applyDiscount
:
const applyDiscount = (price, discount) =>
Box(price)
.map(price => moneyToFloat(price))
.fold(cost =>
Box(discount)
.map(discount => percentToFloat(discount))
.fold(savings => cost - cost * savings));
复制代码
如今能够看一下这组代码的输出了:
const result = applyDiscount('$5.00', '20%');
console.log(String(result)); // "4"
复制代码
若是咱们在moneyToFloat
和percentToFloat
中不进行拆箱(即fold
),那么applyDiscount
就不必在数据转换以前先装箱(即Box
)了:
const moneyToFloat = str =>
Box(str)
.map(s => s.replace(/\$/g, ''))
.map(r => parseFloat(r)); // here we don't fold the result out
const percentToFloat = str =>
Box(str)
.map(str => str.replace(/\%/g, ''))
.map(replaced => parseFloat(replaced))
.map(number => number * 0.01); // here we don't fold the result out
const applyDiscount = (price, discount) =>
moneyToFloat(price)
.fold(cost =>
percentToFloat(discount)
.fold(savings => cost - cost * savings));
const result = applyDiscount('$5.00', '20%');
console.log(String(result)); // "4"
复制代码
Either
进行分支控制Either
的意思是二者之一,不是Right
就是Left
。咱们先实现Right
:
const Right = x => ({
map: f => Right(f(x)),
toString: () => `Right(${x})`
});
const result = Right(3).map(x => x + 1).map(x => x / 2);
console.log(String(result)); // "Right(2)"
复制代码
这里咱们暂且不实现Right
的fold
,而是先来实现Left
:
const Left = x => ({
map: f => Left(x),
toString: () => `Left(${x})`
});
const result = Left(3).map(x => x + 1).map(x => x / 2);
console.log(String(result)); // "Left(3)"
复制代码
Left
容器跟Right
是不一样的,由于Left
彻底忽略了传入的数据转换函数,保持容器内部数据原样。有了Right
和Left
,咱们能够对程序数据流进行分支控制。考虑到程序中常常会存在异常,所以容器一般都是未知类型RightOrLeft
。
接下来咱们实现Right
和Left
容器的fold
方法,若是未知容器是Right
,则使用第二个函数参数g
进行拆箱:
const Right = x => ({
map: f => Right(f(x)),
fold: (f, g) => g(x),
toString: () => `Right(${x})`
});
复制代码
若是未知容器是Left
,则使用第一个函数参数f
进行拆箱:
const Left = x => ({
map: f => Left(x),
fold: (f, g) => f(x),
toString: () => `Left(${x})`
});
复制代码
测试一下Right
和Left
的fold
方法:
const result = Right(2).map(x => x + 1).map(x => x / 2).fold(x => 'error', x => x);
console.log(result); // 1.5
复制代码
const result = Left(2).map(x => x + 1).map(x => x / 2).fold(x => 'error', x => x);
console.log(result); // 'error'
复制代码
借助Either
咱们能够进行程序流程分支控制,例如进行异常处理、null
检查等。
下面看一个例子:
const findColor = name =>
({red: '#ff4444', blue: '#3b5998', yellow: '#fff68f'})[name];
const result = findColor('red').slice(1).toUpperCase();
console.log(result); // "FF4444"
复制代码
这里若是咱们给函数findColor
传入green
,则会报错。所以能够借助Either
进行错误处理:
const findColor = name => {
const found = {red: '#ff4444', blue: '#3b5998', yellow: '#fff68f'}[name];
return found ? Right(found) : Left(null);
};
const result = findColor('green')
.map(c => c.slice(1))
.fold(e => 'no color',
c => c.toUpperCase());
console.log(result); // "no color"
复制代码
更进一步,咱们能够提炼出一个专门用于null
检测的Either
容器,同时简化findColor
代码:
const fromNullable = x =>
x != null ? Right(x) : Left(null); // [!=] will test both null and undefined
const findColor = name =>
fromNullable({red: '#ff4444', blue: '#3b5998', yellow: '#fff68f'}[name]);
复制代码
chain
解决Either
的嵌套问题看一个读取配置文件config.json
的例子,若是位置文件读取失败则提供一个默认端口3000
,命令式代码实现以下:
const fs = require('fs');
const getPort = () => {
try {
const str = fs.readFileSync('config.json');
const config = JSON.parse(str);
return config.port;
} catch (e) {
return 3000;
}
};
const result = getPort();
console.log(result); // 8888 or 3000
复制代码
咱们使用Either
重构:
const fs = require('fs');
const tryCatch = f => {
try {
return Right(f());
} catch (e) {
return Left(e);
}
};
const getPort = () =>
tryCatch(() => fs.readFileSync('config.json'))
.map(c => JSON.parse(c))
.fold(
e => 3000,
obj => obj.port
);
const result = getPort();
console.log(result); // 8888 or 3000
复制代码
重构后就完美了吗?咱们用到了JSON.parse
,若是config.json
文件格式有问题,程序就会报错:
SyntaxError: Unexpected end of JSON input
所以须要针对JSON
解析失败作异常处理,咱们能够继续使用tryCatch
来解决这个问题:
const getPort = () =>
tryCatch(() => fs.readFileSync('config.json'))
.map(c => tryCatch(() => JSON.parse(c)))
.fold(
left => 3000, // 第一个tryCatch失败
right => right.fold( // 第一个tryCatch成功
e => 3000, // JSON.parse失败
c => c.port
)
);
复制代码
此次重构咱们使用了两次tryCatch
,所以致使箱子套了两层,最后须要进行两次拆箱。为了解决这种箱子套箱子的问题,咱们能够给Right
和Left
增长一个方法chain
:
const Right = x => ({
chain: f => f(x),
map: f => Right(f(x)),
fold: (f, g) => g(x),
toString: () => `Right(${x})`
});
const Left = x => ({
chain: f => Left(x),
map: f => Left(x),
fold: (f, g) => f(x),
toString: () => `Left(${x})`
});
复制代码
当咱们使用map
,又不想在数据转换以后又增长一层箱子时,咱们应该使用chain
:
const getPort = () =>
tryCatch(() => fs.readFileSync('config.json'))
.chain(c => tryCatch(() => JSON.parse(c)))
.fold(
e => 3000,
c => c.port
);
复制代码
Either
实现举例const openSite = () => {
if (current_user) {
return renderPage(current_user);
}
else {
return showLogin();
}
};
const openSite = () =>
fromNullable(current_user)
.fold(showLogin, renderPage);
复制代码
const streetName = user => {
const address = user.address;
if (address) {
const street = address.street;
if (street) {
return street.name;
}
}
return 'no street';
};
const streetName = user =>
fromNullable(user.address)
.chain(a => fromNullable(a.street))
.map(s => s.name)
.fold(
e => 'no street',
n => n
);
复制代码
const concatUniq = (x, ys) => {
const found = ys.filter(y => y ===x)[0];
return found ? ys : ys.concat(x);
};
const cancatUniq = (x, ys) =>
fromNullable(ys.filter(y => y ===x)[0])
.fold(null => ys.concat(x), y => ys);
复制代码
const wrapExamples = example => {
if (example.previewPath) {
try {
example.preview = fs.readFileSync(example.previewPath);
}
catch (e) {}
}
return example;
};
const wrapExamples = example =>
fromNullable(example.previewPath)
.chain(path => tryCatch(() => fs.readFileSync(path)))
.fold(
() => example,
preview => Object.assign({preview}, example)
);
复制代码
半群是一种具备concat
方法的类型,而且该concat
方法知足结合律。好比Array
和String
:
const res = "a".concat("b").concat("c");
const res = [1, 2].concat([3, 4].concat([5, 6])); // law of association
复制代码
咱们自定义Sum
半群,Sum
类型用来求和:
const Sum = x => ({
x,
concat: o => Sum(x + o.x),
toString: () => `Sum(${x})`
});
const res = Sum(1).concat(Sum(2));
console.log(String(res)); // "Sum(3)"
复制代码
继续自定义All
半群,All
类型用来级联布尔类型:
const All = x => ({
x,
concat: o => All(x && o.x),
toString: () => `All(${x})`
});
const res = All(true).concat(All(false));
console.log(String(res)); // "All(false)"
复制代码
继续定义First
半群,First
类型链式调用concat
方法不改变其初始值:
const First = x => ({
x,
concat: o => First(x),
toString: () => `First(${x})`
});
const res = First('blah').concat(First('ice cream'));
console.log(String(res)); // "First(blah)"
复制代码
这里先占位,回头再补充。
const acct1 = Map({
name: First('Nico'),
isPaid: All(true),
points: Sum(10),
friends: ['Franklin']
});
const acct2 = Map({
name: First('Nico'),
isPaid: All(false),
points: Sum(2),
friends: ['Gatsby']
});
const res = acct1.concat(acct2);
console.log(res);
复制代码
半群知足结合律,若是半群还具备幺元(单位元),那么就是monoid。幺元与其余元素结合时不会改变那些元素,能够用公式表示以下:
e・a = a・e = a
咱们将半群Sum
升级实现为monoid只需实现一个empty
方法,调用改方法便可获得该monoid的幺元:
const Sum = x => ({
x,
concat: o => Sum(x + o.x),
toString: () => `Sum(${x})`
});
Sum.empty = () => Sum(0);
const res = Sum.empty().concat(Sum(1).concat(Sum(2)));
// const res = Sum(1).concat(Sum(2)).concat(Sum.empty());
console.log(String(res)); // "Sum(3)"
复制代码
接着咱们继续将All
升级实现为monoid:
const All = x => ({
x,
concat: o => All(x && o.x),
toString: () => `All(${x})`
});
All.empty = () => All(true);
const res = All(true).concat(All(true)).concat(All.empty());
console.log(String(res)); // "All(true)"
复制代码
若是咱们尝试着将半群First
也升级为monoid就会发现不可行,好比First('hello').concat(…)
的结果恒为hello
,可是First.empty().concat(First('hello'))
的结果就不必定是hello
了,所以咱们没法将半群First
升级为monoid。这也说明monoid必定是半群,可是半群不必定是monoid。半群须要知足结合律,monoid不只须要知足结合律,还必须存在幺元。
Sum(求和):
const Sum = x => ({
x,
concat: o => Sum(x + o.x),
toString: () => `Sum(${x})`
});
Sum.empty = () => Sum(0);
复制代码
Product(求积):
const Product = x => ({
x,
concat: o => Product(x * o.x),
toString: () => `Product(${x})`
});
Product.empty = () => Product(1);
const res = Product.empty().concat(Product(2)).concat(Product(3));
console.log(String(res)); // "Product(6)"
复制代码
Any(只要有一个为true
即返回true
,不然返回false
):
const Any = x => ({
x,
concat: o => Any(x || o.x),
toString: () => `Any(${x})`
});
Any.empty = () => Any(false);
const res = Any.empty().concat(Any(false)).concat(Any(false));
console.log(String(res)); // "Any(false)"
复制代码
All(全部均为true
才返回true
,不然返回false
):
const All = x => ({
x,
concat: o => All(x && o.x),
toString: () => `All(${x})`
});
All.empty = () => All(true);
const res = All(true).concat(All(true)).concat(All.empty());
console.log(String(res)); // "All(true)"
复制代码
Max(求最大值):
const Max = x => ({
x,
concat: o => Max(x > o.x ? x : o.x),
toString: () => `Max(${x})`
});
Max.empty = () => Max(-Infinity);
const res = Max.empty().concat(Max(100)).concat(Max(200));
console.log(String(res)); // "Max(200)"
复制代码
Min(求最小值):
const Min = x => ({
x,
concat: o => Min(x < o.x ? x : o.x),
toString: () => `Min(${x})`
});
Min.empty = () => Min(Infinity);
const res = Min.empty().concat(Min(100)).concat(Min(200));
console.log(String(res)); // "Min(100)"
复制代码
foldMap
对集合汇总假设咱们须要对一个Sum
集合进行汇总,能够这样实现:
const res = [Sum(1), Sum(2), Sum(3)]
.reduce((acc, x) => acc.concat(x), Sum.empty());
console.log(res); // Sum(6)
复制代码
考虑到这个操做的通常性,能够抽成一个函数fold
。用node
安装immutable
和immutable-ext
。immutable-ext
提供了fold
方法:
const {Map, List} = require('immutable-ext');
const {Sum} = require('./monoid');
const res = List.of(Sum(1), Sum(2), Sum(3))
.fold(Sum.empty());
console.log(res); // Sum(6)
复制代码
也许你会以为fold
接受的参数应该是一个函数,由于前面几节介绍的fold
就是这样的,好比Box
和Right
:
Box(3).fold(x => x); // 3
Right(3).fold(e => e, x => x); // 3
复制代码
没错,不过fold
的本质就是拆箱。前面对Box
和Right
类型拆箱是将其值取出来;而如今对集合拆箱则是为了将集合的汇总结果取出来。而将一个集合中的多个值汇总成一个值就须要传入初始值Sum.empty()
。所以当你看到fold
时,应该当作是为了从一个类型中取值出来,而这个类型多是一个仅含一个值的类型(好比Box
,Right
),也多是一个monoid集合。
咱们继续看另一种集合Map
:
const res = Map({brian: Sum(3), sara: Sum(5)})
.fold(Sum.empty());
console.log(res); // Sum(8)
复制代码
这里的Map
是monoid集合,若是是普通数据集合能够先使用集合的map
方法将该集合转换成monoid集合:
const res = Map({brian: 3, sara: 5})
.map(Sum)
.fold(Sum.empty());
console.log(res); // Sum(8)
复制代码
const res = List.of(1, 2, 3)
.map(Sum)
.fold(Sum.empty());
console.log(res); // Sum(6)
复制代码
咱们能够把这种对普通数据类型集合调用map
转换成monoid类型集合,而后再调用fold
进行数据汇总的操做抽出来,即为foldMap
:
const res = List.of(1, 2, 3)
.foldMap(Sum, Sum.empty());
console.log(res); // Sum(6)
复制代码
LazyBox
延迟求值首先回顾一下前面Box
的例子:
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
toString: () => `Box(${x})`
});
const res = Box(' 64')
.map(s => s.trim())
.map(s => parseInt(s))
.map(i => i + 1)
.map(i => String.fromCharCode(i))
.fold(x => x.toLowerCase());
console.log(String(res)); // a
复制代码
这里进行了一系列的数据转换,最后转换成了a
。如今咱们能够定义一个LazyBox
,延迟执行这一系列数据转换函数,直到最后扣动扳机:
const LazyBox = g => ({
map: f => LazyBox(() => f(g())),
fold: f => f(g())
});
const res = LazyBox(() => ' 64')
.map(s => s.trim())
.map(s => parseInt(s))
.map(i => i + 1)
.map(i => String.fromCharCode(i))
.fold(x => x.toLowerCase());
console.log(res); // a
复制代码
LazyBox
的参数是一个参数为空的函数。在LazyBox
上调用map
并不会当即执行传入的数据转换函数,每调用一次map
待执行函数队列中就会多一个函数,直到最后调用fold
扣动扳机,前面全部的数据转换函数一触一发,一个接一个的执行。这种模式有助于实现纯函数。
Task
中捕获反作用本节依然是讨论Lazy特性,只不过基于data.task
库,该库能够经过npm安装。假设咱们要实现一个发射火箭的函数,若是咱们这样实现,那么该函数显然不是纯函数:
const launchMissiles = () =>
console.log('launch missiles!'); // 使用console.log模仿发射火箭
复制代码
若是使用data.task
能够借助其Lazy特性,延迟执行:
const Task = require('data.task');
const launchMissiles = () =>
new Task((rej, res) => {
console.log('launch missiles!');
res('missile');
});
复制代码
显然这样实现launchMissiles
即为纯函数。咱们能够继续在其基础上组合其余逻辑:
const app = launchMissiles().map(x => x + '!');
app
.map(x => x + '!')
.fork(
e => console.log('err', e),
x => console.log('success', x)
);
// launch missiles!
// success missile!!
复制代码
调用fork
方法才会扣动扳机,执行前面定义的Task
以及一系列数据转换函数,若是不调用fork
,Task
中的console.log
操做就不会执行。
Task
处理异步任务假设咱们要实现读文件,替换文件内容,而后写文件的操做,命令式代码以下:
const fs = require('fs');
const app = () =>
fs.readFile('config.json', 'utf-8', (err, contents) => {
if (err) throw err;
const newContents = contents.replace(/8/g, '6');
fs.writeFile('config1.json', newContents,
(err, success) => {
if (err) throw err;
console.log('success');
})
});
app();
复制代码
这里实现的app
内部会抛出异常,不是纯函数。咱们能够借助Task
重构以下:
const Task = require('data.task');
const fs = require('fs');
const readFile = (filename, enc) =>
new Task((rej, res) =>
fs.readFile(filename, enc, (err, contents) =>
err ? rej(err) : res(contents)));
const writeFile = (filename, contents) =>
new Task((rej, res) =>
fs.writeFile(filename, contents, (err, success) =>
err ? rej(err) : res(success)));
const app = () =>
readFile('config.json', 'utf-8')
.map(contents => contents.replace(/8/g, '6'))
.chain(contents => writeFile('config1.json', contents));
app().fork(
e => console.log(e),
x => console.log('success')
);
复制代码
这里实现的app
是纯函数,调用app().fork
才会执行一系列动做。再看看data.task
官网的顺序读两个文件的例子:
const fs = require('fs');
const Task = require('data.task');
const readFile = path =>
new Task((rej, res) =>
fs.readFile(path, 'utf-8', (error, contents) =>
error ? rej(error) : res(contents)));
const concatenated = readFile('Task_test_file1.txt')
.chain(a =>
readFile('Task_test_file2.txt')
.map(b => a + b));
concatenated.fork(console.error, console.log);
复制代码
Functor是具备map
方法的类型,而且须要知足下面两个条件:
fx.map(f).map(g) == fx.map(x => g(f(x)))
fx.map(id) == id(fx), where const id = x => x
以Box
类型为例说明:
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
const res1 = Box('squirrels')
.map(s => s.substr(5))
.map(s => s.toUpperCase());
const res2 = Box('squirrels')
.map(s => s.substr(5).toUpperCase());
console.log(res1, res2); // Box(RELS) Box(RELS)
复制代码
显然Box
知足第一个条件。注意这里的s = > s.substr(5).toUpperCase()
其实本质上跟g(f(x))
是同样的,咱们彻底从新定义成下面这种形式,不要被形式迷惑:
const f = s => s.substr(5);
const g = s => s.toUpperCase();
const h = s => g(f(s));
const res = Box('squirrels')
.map(h);
console.log(res); // Box(RELS)
复制代码
接下来咱们看是否知足第二个条件:
const id = x => x;
const res1 = Box('crayons').map(id);
const res2 = id(Box('crayons'));
console.log(res1, res2); // Box(crayons) Box(crayons)
复制代码
显然也知足第二个条件。
of
方法将值放入Pointed Functorpointed functor是具备of
方法的functor,of
能够理解成使用一个初始值来填充functor。以Box
为例说明:
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
Box.of = x => Box(x);
const res = Box.of(100);
console.log(res); // Box(100)
复制代码
这里再举个functor的例子,IO functor:
const R = require('ramda');
const IO = x => ({
x, // here x is a function
map: f => IO(R.compose(f, x)),
fold: f => f(x) // get out x
});
IO.of = x => IO(x);
复制代码
IO是一个值为函数的容器,细心的话你会发现这就是前面的值为函数的Box
容器。借助IO functor,咱们能够纯函数式的处理一些IO操做了,由于读写操做就好像所有放入了队列同样,直到最后调用IO内部的函数时才会扣动扳机执行一系列操做,试一下:
const R = require('ramda');
const {IO} = require('./IO');
const fake_window = {
innerWidth: '1000px',
location: {
href: "http://www.baidu.com/cpd/fe"
}
};
const io_window = IO(() => fake_window);
const getWindowInnerWidth = io_window
.map(window => window.innerWidth)
.fold(x => x);
const split = x => s => s.split(x);
const getUrl = io_window
.map(R.prop('location'))
.map(R.prop('href'))
.map(split('/'))
.fold(x => x);
console.log(getWindowInnerWidth()); // 1000px
console.log(getUrl()); // [ 'http:', '', 'www.baidu.com', 'cpd', 'fe' ]
复制代码
functor能够将一个函数做用到一个包着的(这里“包着”意思是值存在于箱子内,下同)值上面:
Box(1).map(x => x + 1); // Box(2)
复制代码
applicative functor能够将一个包着的函数做用到一个包着的值上面:
const add = x => x + 1;
Box(add).ap(Box(1)); // Box(2)
复制代码
而monod能够将一个返回箱子类型的函数做用到一个包着的值上面,重点是做用以后包装层数不增长:
先看个Box
functor的例子:
const Box = x => ({
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
const res = Box(1)
.map(x => Box(x))
.map(x => Box(x)); // Box(Box(Box(1)))
console.log(res); // Box([object Object])
复制代码
这里咱们连续调用map
而且map
时传入的函数的返回值是箱子类型,显然这样会致使箱子的包装层数不断累加,咱们能够给Box
增长join
方法来拆包装:
const Box = x => ({
map: f => Box(f(x)),
join: () => x,
fold: f => f(x),
inspect: () => `Box(${x})`
});
const res = Box(1)
.map(x => Box(x))
.join()
.map(x => Box(x))
.join();
console.log(res); // Box(1)
复制代码
这里定义join
仅仅是为了说明拆包装这个操做,咱们固然可使用fold
完成相同的功能:
const Box = x => ({
map: f => Box(f(x)),
join: () => x,
fold: f => f(x),
inspect: () => `Box(${x})`
});
const res = Box(1)
.map(x => Box(x))
.fold(x => x)
.map(x => Box(x))
.fold(x => x);
console.log(res); // Box(1)
复制代码
考虑到.map(...).join()
的通常性,咱们能够为Box
增长一个方法chain
完成这两步操做:
const Box = x => ({
map: f => Box(f(x)),
join: () => x,
chain: f => Box(x).map(f).join(),
fold: f => f(x),
inspect: () => `Box(${x})`
});
const res = Box(1)
.chain(x => Box(x))
.chain(x => Box(x));
console.log(res); // Box(1)
复制代码
这个很是简单,直接举例,能看懂这些例子就明白柯里化了:
const modulo = dvr => dvd => dvd % dvr;
const isOdd = modulo(2); // 求奇数
const filter = pred => xs => xs.filter(pred);
const getAllOdds = filter(isOdd);
const res1 = getAllOdds([1, 2, 3, 4]);
console.log(res1); // [1, 3]
const map = f => xs => xs.map(f);
const add = x => y => x + y;
const add1 = add(1);
const allAdd1 = map(add1);
const res2 = allAdd1([1, 2, 3]);
console.log(res2); // [2, 3, 4]
复制代码
前面介绍的Box
是一个functor,咱们为其添加ap
方法,将其升级成applicative functor:
const Box = x => ({
ap: b2 => b2.map(x), // here x is a function
map: f => Box(f(x)),
fold: f => f(x),
inspect: () => `Box(${x})`
});
const res = Box(x => x + 1).ap(Box(2));
console.log(res); // Box(3)
复制代码
这里Box
内部是一个一元函数,咱们也可使用柯里化后的多元函数:
const add = x => y => x + y;
const res = Box(add).ap(Box(2));
console.log(res); // Box([Function])
复制代码
显然咱们applicative functor上调用一次ap
便可消掉一个参数,这里res
内部存的是仍然是一个函数:y => 2 + y
,只不过消掉了参数x
。咱们能够连续调用ap
方法:
const res = Box(add).ap(Box(2)).ap(Box(3));
console.log(res); // Box(5)
复制代码
稍加思考咱们会发现对于applicative functor,存在下面这个恒等式:
F(x).map(f) = F(f).ap(F(x))
即在一个保存值x
的functor上调用map(f)
,恒等于在保存函数f
的functor上调用ap(F(x))
。
接着咱们实现一个处理applicative functor的工具函数liftA2
:
const liftA2 = (f, fx, fy) =>
F(f).ap(fx).ap(fy);
复制代码
可是这里须要知道具体的functor类型F
,所以借助于前面的恒等式,咱们继续定义下面的通常形式liftA2
:
const liftA2 = (f, fx, fy) =>
fx.map(f).ap(fy);
复制代码
试一下:
const res1 = Box(add).ap(Box(2)).ap(Box(4));
const res2 = liftA2(add, Box(2), Box(4)); // utilize helper function liftA2
console.log(res1); // Box(6)
console.log(res2); // Box(6)
复制代码
固然咱们也能够定义相似的liftA3
,liftA4
等工具函数:
const liftA3 = (f, fx, fy, fz) =>
fx.map(f).ap(fy).ap(fz);
复制代码
首先来定义either
:
const Right = x => ({
ap: e2 => e2.map(x), // declare as a applicative, here x is a function
chain: f => f(x), // declare as a monad
map: f => Right(f(x)),
fold: (f, g) => g(x),
inspect: () => `Right(${x})`
});
const Left = x => ({
ap: e2 => e2.map(x), // declare as a applicative, here x is a function
chain: f => Left(x), // declare as a monad
map: f => Left(x),
fold: (f, g) => f(x),
inspect: () => `Left(${x})`
});
const fromNullable = x =>
x != null ? Right(x) : Left(null); // [!=] will test both null and undefined
const either = {
Right,
Left,
of: x => Right(x),
fromNullable
};
复制代码
能够看出either
既是monad又是applicative functor。
假设咱们要计算页面上除了header
和footer
以外的高度:
const $ = selector =>
either.of({selector, height: 10}); // fake DOM selector
const getScreenSize = (screen, header, footer) =>
screen - (header.height + footer.height);
复制代码
若是使用monod
的chain
方法,能够这样实现:
const res = $('header')
.chain(header =>
$('footer').map(footer =>
getScreenSize(800, header, footer)));
console.log(res); // Right(780)
复制代码
也可使用applicative
实现,不过首先须要柯里化getScreenSize
:
const getScreenSize = screen => header => footer =>
screen - (header.height + footer.height);
const res1 = either.of(getScreenSize(800))
.ap($('header'))
.ap($('footer'));
const res2 = $('header')
.map(getScreenSize(800))
.ap($('footer'));
const res3 = liftA2(getScreenSize(800), $('header'), $('footer'));
console.log(res1, res2, res3); // Right(780) Right(780) Right(780)
复制代码
本节介绍使用applicative functor实现下面这种模式:
for (x in xs) {
for (y in ys) {
for (z in zs) {
// your code here
}
}
}
复制代码
使用applicative functor重构以下:
const {List} = require('immutable-ext');
const merch = () =>
List.of(x => y => z => `${x}-${y}-${z}`)
.ap(List(['teeshirt', 'sweater']))
.ap(List(['large', 'medium', 'small']))
.ap(List(['black', 'white']));
const res = merch();
console.log(res);
复制代码
假设咱们要发起两次读数据库的请求:
const Task = require('data.task');
const Db = ({
find: id =>
new Task((rej, res) =>
setTimeOut(() => {
console.log(res);
res({id: id, title: `Project ${id}`})
}, 5000))
});
const report = (p1, p2) =>
`Report: ${p1.title} compared to ${p2.title}`;
复制代码
若是使用monad
的chain
实现,那么两个异步事件只能顺序执行:
Db.find(20).chain(p1 =>
Db.find(8).map(p2 =>
report(p1, p2)))
.fork(console.error, console.log);
复制代码
使用applicatives重构:
Task.of(p1 => p2 => report(p1, p2))
.ap(Db.find(20))
.ap(Db.find(8))
.fork(console.error, console.log);
复制代码
假设咱们准备读取一组文件:
const fs = require('fs');
const Task = require('data.task');
const futurize = require('futurize').futurize(Task);
const {List} = require('immutable-ext');
const readFile = futurize(fs.readFile);
const files = ['box.js', 'config.json'];
const res = files.map(fn => readFile(fn, 'utf-8'));
console.log(res);
// [ Task { fork: [Function], cleanup: [Function] },
// Task { fork: [Function], cleanup: [Function] } ]
复制代码
这里res
是一个Task
数组,而咱们想要的是Task([])
这种类型,相似promise.all()
的功能。咱们能够借助traverse
方法使Task
类型从数组里跳到外面:
[Task] => Task([])
实现以下:
const files = List(['box.js', 'config.json']);
files.traverse(Task.of, fn => readFile(fn, 'utf-8'))
.fork(console.error, console.log);
复制代码
假设咱们准备发起一组http请求:
const fs = require('fs');
const Task = require('data.task');
const {List, Map} = require('immutable-ext');
const httpGet = (path, params) =>
Task.of(`${path}: result`);
const res = Map({home: '/', about: '/about', blog: '/blod'})
.map(route => httpGet(route, {}));
console.log(res);
// Map { "home": Task, "about": Task, "blog": Task }
复制代码
这里res
是一个值为Task
的Map
,而咱们想要的是Task({})
这种类型,相似promise.all()
的功能。咱们能够借助traverse
方法使Task
类型从Map
里跳到外面:
{Task} => Task({})
实现以下:
Map({home: '/', about: '/about', blog: '/blod'})
.traverse(Task.of, route => httpGet(route, {}))
.fork(console.error, console.log);
// Map { "home": "/: result", "about": "/about: result", "blog": "/blod: result" }
复制代码
本节介绍一种functor如何转换成另一种functor。例如将either
转换成Task
:
const {Right, Left, fromNullable} = require('./either');
const Task = require('data.task');
const eitherToTask = e =>
e.fold(Task.rejected, Task.of);
eitherToTask(Right('nightingale'))
.fork(
e => console.error('err', e),
r => console.log('res', r)
); // res nightingale
eitherToTask(Left('nightingale'))
.fork(
e => console.error('err', e),
r => console.log('res', r)
); // err nightingale
复制代码
将Box
转换成Either
:
const {Right, Left, fromNullable} = require('./either');
const Box = require('./box');
const boxToEither = b =>
b.fold(Right);
const res = boxToEither(Box(100));
console.log(res); // Right(100)
复制代码
你可能会疑惑为何boxToEither
要转换成Right
,而不是Left
,缘由就是本节讨论的类型转换须要知足该条件:
nt(fx).map(f) == nt(fx.map(f))
其中nt
是natural transform的缩写,即天然类型转换,全部知足该公式的函数均为天然类型转换。接着讨论boxToEither
,若是前面转换成Left
,咱们看下是否还能知足该公式:
const boxToEither = b =>
b.fold(Left);
const res1 = boxToEither(Box(100)).map(x => x * 2);
const res2 = boxToEither(Box(100).map(x => x * 2));
console.log(res1, res2); // Left(100) Left(200)
复制代码
显然不知足上面的条件。
再看一个天然类型转换函数first
:
const first = xs =>
fromNullable(xs[0]);
const res1 = first([1, 2, 3]).map(x => x + 1);
const res2 = first([1, 2, 3].map(x => x + 1));
console.log(res1, res2); // Right(2) Right(2)
复制代码
前面的公式代表,对于一个functor
,先进行天然类型转换再map
等价于先map
再进行天然类型转换。
先看下first
的一个用例:
const {fromNullable} = require('./either');
const first = xs =>
fromNullable(xs[0]);
const largeNumbers = xs =>
xs.filter(x => x > 100);
const res = first(largeNumbers([2, 400, 5, 1000]).map(x => x * 2));
console.log(res); // Right(800)
复制代码
这种实现没什么问题,不过这里将large numbers的每一个值都进行了乘2的map
,而我么最后的结果仅仅须要第一个值,所以借用天然类型转换公式咱们能够改为下面这种形式:
const res = first(largeNumbers([2, 400, 5, 1000])).map(x => x * 2);
console.log(res); // Right(800)
复制代码
再看一个稍微复杂点的例子:
const {Right, Left} = require('./either');
const Task = require('data.task');
const fake = id => ({
id,
name: 'user1',
best_friend_id: id + 1
}); // fake user infomation
const Db = ({
find: id =>
new Task((rej, res) =>
res(id > 2 ? Right(fake(id)) : Left('not found')))
}); // fake database
const eitherToTask = e =>
e.fold(Task.rejected, Task.of);
复制代码
这里咱们模拟了一个数据库以及一些用户信息,并假设数据库中只可以查到id
大于2的用户。
如今咱们要查找某个用户的好朋友的信息:
Db.find(3) // Task(Right(user))
.map(either =>
either.map(user => Db.find(user.best_friend_id))) // Task(Either(Task(Either)))
复制代码
若是这里使用chain
,看一下效果如何:
Db.find(3) // Task(Right(user))
.chain(either =>
either.map(user => Db.find(user.best_friend_id))) // Either(Task(Either))
复制代码
这样调用完以后也有有问题:容器的类型从Task
变成了Either
,这也不是咱们想看到的。下面咱们借助天然类型转换重构一下:
Db.find(3) // Task(Right(user))
.map(eitherToTask) // Task(Task(user))
复制代码
为了去掉一层包装,咱们改用chain
:
Db.find(3) // Task(Right(user))
.chain(eitherToTask) // Task(user)
.chain(user =>
Db.find(user.best_friend_id)) // Task(Right(user))
.chain(eitherToTask)
.fork(
console.error,
console.log
); // { id: 4, name: 'user1', best_friend_id: 5 }
复制代码
这里讨论的同构不是“先后端同构”的同构,而是一对知足以下要求的函数:
from(to(x)) == x
to(from(y)) == y
若是可以找到一对函数知足上述要求,则说明一个数据类型x
具备与另外一个数据类型y
相同的信息或结构,此时咱们说数据类型x
和数据类型y
是同构的。好比String
和[char]
就是同构的:
const Iso = (to, from) =>({
to,
from
});
// String ~ [char]
const chars = Iso(s => s.split(''), arr => arr.join(''));
const res1 = chars.from(chars.to('hello world'));
const res2 = chars.to(chars.from(['a', 'b', 'c']));
console.log(res1, res2); // hello world [ 'a', 'b', 'c' ]
复制代码
这有什么用呢?咱们举个例子:
const filterString = (str1, str2, pred) =>
chars.from(chars.to(str1 + str2).filter(pred));
const res1 = filterString('hello', 'HELLO', x => x.match(/[aeiou]/ig));
console.log(res1); // eoEO
const toUpperCase = (arr1, arr2) =>
chars.to(chars.from(arr1.concat(arr2)).toUpperCase());
const res2 = toUpperCase(['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd']);
console.log(res2); // [ 'H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D' ]
复制代码
这里咱们借助Array
的filter
方法来过滤String
中的字符;借助String
的toUpperCase
方法来处理字符数组的大小写转换。可见有了同构,咱们能够在两种不一样的数据类型之间互相转换并调用其方法。
课程最后三节的实战例子见:实战。