JavaScript 函數(shù)式編程解析(上)
一些必要的概念
純函數(shù)(Pure Function)
Pure function 意指相同的輸入,永遠(yuǎn)會(huì)得到相同的輸出,而且沒(méi)有任何顯著的副作用。
純函數(shù)就是數(shù)學(xué)里的函數(shù),這也是函數(shù)式編程的全部。
副作用
副作用是在計(jì)算結(jié)果的過(guò)程中,系統(tǒng)狀態(tài)的一種改變,或是外部世界可觀察的交互作用。
副作用可以包含,但不限于:
更改文件系統(tǒng)
在資料庫(kù)寫入紀(jì)錄
發(fā)送一個(gè) http 請(qǐng)求
狀態(tài)變化
打印到屏幕/ log
DOM 查詢
存取系統(tǒng)狀態(tài)
概括來(lái)說(shuō),任何 function 與外部環(huán)境的交互都是副作用。
柯里化(curry)
使用更少的參數(shù)調(diào)用一個(gè)函數(shù),返回一個(gè)接受剩余參數(shù)的函數(shù)。舉例如下:
const add = x => y => x + y;
const increment = add(1);
const addTen = add(10);
increment(2); // 3
addTen(2); // 12
函數(shù)式編程的優(yōu)勢(shì)
確定性(可預(yù)測(cè)性、數(shù)據(jù)不可變),同樣的輸入必然得到相同的輸出可以使用數(shù)學(xué)定律
// 結(jié)合律(associative)
add(add(x, y), z) === add(x, add(y, z));
// 交換律(commutative)
add(x, y) === add(y, x);
// 同一律(identity)
add(x, 0) === x;
// 分配律(distributive)
multiply(x, add(y,z)) === add(multiply(x, y), multiply(x, z));
函數(shù)式編程的適用場(chǎng)景
可變狀態(tài)(mutable state) 不受限的副作用(unrestricted side effects) 無(wú)原則設(shè)計(jì)(unprincipled design)
函數(shù)是一等公民的意義
在 JavaScript 中,函數(shù)是一等公民,它意味著函數(shù)就跟其他任何數(shù)據(jù)類型一樣,并沒(méi)有什么特殊之處——可以存儲(chǔ)在數(shù)組中,作為函數(shù)的參數(shù)傳遞、賦值給變量,等等。作為“一等公民”,函數(shù)的意義至少有如下幾點(diǎn):
有助于減少不必要的重構(gòu)
// 如果renderPost功能發(fā)生變化,必須改變包裝函數(shù)
httpGet('/post/2', json => renderPost(json));
// 例如增加一個(gè)err
httpGet('/post/2', (json, err) => renderPost(json, err));
// 如果我們把它寫成一個(gè)一等公民函數(shù),那么就不需要變了
httpGet('/post/2', renderPost);
有助于增加通用性和可重用性
// 專門為特定的功能準(zhǔn)備
const validArticles = articles =>
articles.filter(article => article !== null && article !== undefined),
// 看上去有無(wú)限的通用性和可重用性
const compact = xs => xs.filter(x => x !== null && x !== undefined);
不需要使用 this,但是需要注意適配外部API
const fs = require('fs');
// scary
fs.readFile('freaky_friday.txt', Db.save);
// less so
fs.readFile('freaky_friday.txt', Db.save.bind(Db));
純函數(shù)的價(jià)值
可緩存
const memoize = (f) => {
const cache = {};
return (...args) => {
const argStr = JSON.stringify(args);
cache[argStr] = cache[argStr] || f(...args);
return cache[argStr];
};
};
const squareNumber = memoize(x => x * x);
squareNumber(4); // 16
squareNumber(4); // 16, 返回輸入4的緩存結(jié)果
可移植性/自文檔化(Portable / Self-documenting)
// impure
const signUp = (attrs) => {
const user = saveUser(attrs);
welcomeUser(user);
};
// pure
const signUp = (Db, Email, attrs) => () => {
const user = saveUser(Db, attrs);
welcomeUser(Email, user);
};
純函數(shù)把所有可能改變輸出的變量Db和Email,都作為函數(shù)簽名,這樣我們就能知道函數(shù)是做什么的,依賴什么參數(shù)——提供了更多的信息。可移植性是 JS 的一個(gè)強(qiáng)大特性,函數(shù)會(huì)通過(guò) socket 序列化并傳輸,意味著在 web worker 中我們可以運(yùn)行所有代碼。
可測(cè)試的(Testable):利用特性,只需要給出輸入和斷言的輸出即可。 可推理的(Reasonable):同理 并行代碼(Parallel Code):由于不需要共享內(nèi)存,所以可以并行處理純函數(shù)
柯里化(Currying)
// curry :: ((a, b, ...) -> c) -> a -> b -> ... -> c
function curry(fn) {
const arity = fn.length;
return function $curry(...args) {
if (args.length < arity) {
return $curry.bind(null, ...args);
}
return fn.call(null, ...args);
};
}
const match = curry((what, s) => s.match(what));
const replace = curry((what, replacement, s) => s.replace(what, replacement));
const filter = curry((f, xs) => xs.filter(f));
const map = curry((f, xs) => xs.map(f));
通過(guò)以上的柯里化函數(shù),我們可以把函數(shù)式編程變得簡(jiǎn)潔,沒(méi)有冗余。盡管有多個(gè)參數(shù),我們?nèi)匀豢梢员A魯?shù)學(xué)函數(shù)的定義。
match(/r/g, 'hello world'); // [ 'r' ]
const hasLetterR = match(/r/g); // x => x.match(/r/g)
hasLetterR('hello world'); // [ 'r' ]
hasLetterR('just j and s and t etc'); // null
filter(hasLetterR, ['rock and roll', 'smooth jazz']); // ['rock and roll']
const removeStringsWithoutRs = filter(hasLetterR); // xs => xs.filter(x => x.match(/r/g))
removeStringsWithoutRs(['rock and roll', 'smooth jazz', 'drum circle']); // ['rock and roll', 'drum circle']
const noVowels = replace(/[aeiou]/ig); // (r,x) => x.replace(/[aeiou]/ig, r)
const censored = noVowels('*'); // x => x.replace(/[aeiou]/ig, '*')
censored('Chocolate Rain'); // 'Ch*c*l*t* R**n'
組合(Composing)
Composing 就是把函數(shù)像“管道”一樣組合起來(lái)。下面展示最簡(jiǎn)單的組合示例。
const composes = (f, g) => x => f(g(x));
const toUpperCase = x => x.toUpperCase();
const exclaim = x => `${x}!`;
const shout = compose(exclaim, toUpperCase);
shout('send in the clowns'); // "SEND IN THE CLOWNS!"
以下是一個(gè)通用的 compose 函數(shù):
const compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];
因?yàn)?compose 也是純函數(shù),同樣滿足分配律:
// 滿足分配律
compose(f, compose(g, h)) === compose(compose(f, g), h);
所以不管傳參的順序如何,它都返回相同的結(jié)果,非常強(qiáng)大 ??
const arg = ['jumpkick', 'roundhouse', 'uppercut'];
const lastUpper = compose(toUpperCase, head, reverse);
const loudLastUpper = compose(exclaim, toUpperCase, head, reverse);
lastUpper(arg); // 'UPPERCUT'
loudLastUpper(arg); // 'UPPERCUT!'
Pointfree 風(fēng)格
Pointfree 的意思是不使用所要操作的數(shù)據(jù),只合成運(yùn)算過(guò)程。下面是使用Ramda[1]函數(shù)庫(kù)的pipe方法實(shí)現(xiàn) Pointfree 的例子,選自阮一峰老師的《Pointfree 編程風(fēng)格指南》[2]。
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit';
上面字符串最長(zhǎng)的單詞有多少個(gè)字符呢?先定義一些基本運(yùn)算:
// 以空格分割單詞
var splitBySpace = s => s.split(' ');
// 每個(gè)單詞的長(zhǎng)度
var getLength = w => w.length;
// 詞的數(shù)組轉(zhuǎn)換成長(zhǎng)度的數(shù)組
var getLengthArr = arr => R.map(getLength, arr);
// 返回較大的數(shù)字
var getBiggerNumber = (a, b) => a > b ? a : b;
// 返回最大的一個(gè)數(shù)字
var findBiggestNumber = arr => R.reduce(getBiggerNumber, 0, arr);
然后把基本運(yùn)算合成為一個(gè)函數(shù):
var getLongestWordLength = R.pipe(
splitBySpace,
getLengthArr,
findBiggestNumber
);
getLongestWordLength(str) // 11
可以看到,整個(gè)運(yùn)算由三個(gè)步驟構(gòu)成,每個(gè)步驟都有語(yǔ)義化的名稱,非常的清晰。這就是 Pointfree 風(fēng)格的優(yōu)勢(shì)。Ramda 提供了很多現(xiàn)成的方法,可以直接使用這些方法,省得自己定義一些常用函數(shù)(查看完整代碼[3])。
// 上面代碼的另一種寫法
var getLongestWordLength = R.pipe(
R.split(' '),
R.map(R.length),
R.reduce(R.max, 0)
);
再看一個(gè)實(shí)戰(zhàn)的例子,拷貝自 Scott Sauyet 的文章《Favoring Curry》[4]。那篇文章能幫助你深入理解柯里化,強(qiáng)烈推薦閱讀。下面是一段服務(wù)器返回的 JSON 數(shù)據(jù)。
現(xiàn)在要求是,找到用戶 Scott 的所有未完成任務(wù),并按到期日期升序排列。
過(guò)程式編程的代碼如下(查看完整代碼[5])。
上面代碼不易讀,出錯(cuò)的可能性很大。現(xiàn)在使用 Pointfree 風(fēng)格改寫(查看完整代碼[6])。
const getIncompleteTaskSummaries = (name) => {
return fetchData()
.then(R.prop('tasks'))
.then(R.filter(R.propEq('username', name)))
.then(R.reject(R.propEq('complete', true)))
.then(R.map(R.pick(['id', 'dueDate', 'title', 'priority'])))
.then(R.sortBy(R.prop('dueDate')))
}
上面代碼就變得清晰很多了。
常用 Pointfree 純函數(shù)的實(shí)現(xiàn)
下面的實(shí)現(xiàn)僅僅為了基本演示,如果考慮實(shí)際開(kāi)發(fā),請(qǐng)參考ramda[7],lodash[8], 或folktale[9]。
// curry :: ((a, b, ...) -> c) -> a -> b -> ... -> c
function curry(fn) {
const arity = fn.length;
return function $curry(...args) {
if (args.length < arity) {
return $curry.bind(null, ...args);
}
return fn.call(null, ...args);
};
}
// compose :: ((y -> z), (x -> y), ..., (a -> b)) -> a -> z
const compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];
// forEach :: (a -> ()) -> [a] -> ()
const forEach = curry((fn, xs) => xs.forEach(fn));
// map :: Functor f => (a -> b) -> f a -> f b
const map = curry((fn, f) => f.map(fn));
// reduce :: (b -> a -> b) -> b -> [a] -> b
const reduce = curry((fn, zero, xs) => xs.reduce(fn, zero));
// replace :: RegExp -> String -> String -> String
const replace = curry((re, rpl, str) => str.replace(re, rpl));
// sortBy :: Ord b => (a -> b) -> [a] -> [a]
const sortBy = curry((fn, xs) => xs.sort((a, b) => {
if (fn(a) === fn(b)) {
return 0;
}
return fn(a) > fn(b) ? 1 : -1;
}));
// prop :: String -> Object -> a
const prop = curry((p, obj) => obj[p]);
關(guān)于更多 Pointfree 純函數(shù)的實(shí)現(xiàn)可以參考Pointfree Utilities[10]。
參考
《Professor Frisby’s Mostly Adequate Guide to Functional Programming》[11],翻譯版本為《JS 函數(shù)式編程指南中文版》[12]
Pointfree Javascript[13]
Favoring Curry[14]
參考資料
Ramda: http://www.ruanyifeng.com/blog/2017/03/ramda.html
[2]《Pointfree 編程風(fēng)格指南》: http://www.ruanyifeng.com/blog/2017/03/pointfree.html
[3]完整代碼: http://jsbin.com/vutoxis/edit?js,console
[4]《Favoring Curry》: http://fr.umio.us/favoring-curry/
[5]完整代碼: http://jsbin.com/kiqequ/edit?js,console
[6]完整代碼: https://jsbin.com/dokajarilo/1/edit?js,console
[7]ramda: https://ramdajs.com/
[8]lodash: https://lodash.com/
[9]folktale: http://folktale.origamitower.com/
[10]Pointfree Utilities: https://mostly-adequate.gitbook.io/mostly-adequate-guide/appendix_c
[11]《Professor Frisby’s Mostly Adequate Guide to Functional Programming》: https://github.com/MostlyAdequate/mostly-adequate-guide
[12]《JS 函數(shù)式編程指南中文版》: https://jigsawye.gitbooks.io/mostly-adequate-guide/content/SUMMARY.md
[13]Pointfree Javascript: http://lucasmreis.github.io/blog/pointfree-javascript/
[14]Favoring Curry: http://fr.umio.us/favoring-curry/
