JavaScript 函數式編程解析(上)
一些必要的概念
- 純函數(Pure Function)
Pure function 意指相同的輸入,永遠會得到相同的輸出,而且沒有任何顯著的副作用。
純函數就是數學裏的函數,這也是函數式編程的全部。
- 副作用
副作用_是在計算結果的過程中,系統狀態的一種改變,或是外部世界可觀察的_交互作用。
副作用可以包含,但不限於:
-
更改文件系統
-
在資料庫寫入紀錄
-
發送一個 http 請求
-
狀態變化
-
打印到屏幕 / log
-
DOM 查詢
-
存取系統狀態
概括來說,任何 function 與外部環境的交互都是副作用。
- 柯里化(curry)
使用更少的參數調用一個函數,返回一個接受剩餘參數的函數。舉例如下:
const add = x => y => x + y;
const increment = add(1);
const addTen = add(10);
increment(2); // 3
addTen(2); // 12
函數式編程的優勢
-
確定性(可預測性、數據不可變),同樣的輸入必然得到相同的輸出
-
可以使用數學定律
// 結合律(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));
函數式編程的適用場景
-
可變狀態(mutable state)
-
不受限的副作用(unrestricted side effects)
-
無原則設計(unprincipled design)
函數是一等公民的意義
在 JavaScript 中,函數是一等公民,它意味着函數就跟其他任何數據類型一樣,並沒有什麼特殊之處——可以存儲在數組中,作爲函數的參數傳遞、賦值給變量,等等。作爲 “一等公民”,函數的意義至少有如下幾點:
-
有助於減少不必要的重構
// 如果renderPost功能發生變化,必須改變包裝函數
httpGet('/post/2', json => renderPost(json));
// 例如增加一個err
httpGet('/post/2', (json, err) => renderPost(json, err));
// 如果我們把它寫成一個一等公民函數,那麼就不需要變了
httpGet('/post/2', renderPost);
-
有助於增加通用性和可重用性
// 專門爲特定的功能準備
const validArticles = articles =>
articles.filter(article => article !== null && article !== undefined),
// 看上去有無限的通用性和可重用性
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));
純函數的價值
-
可緩存
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的緩存結果
-
可移植性/自文檔化(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);
};
純函數把所有可能改變輸出的變量Db
和Email
,都作爲函數簽名,這樣我們就能知道函數是做什麼的,依賴什麼參數——提供了更多的信息。可移植性是 JS 的一個強大特性,函數會通過 socket 序列化並傳輸,意味着在 web worker 中我們可以運行所有代碼。
-
可測試的(Testable):利用特性,只需要給出輸入和斷言的輸出即可。
-
可推理的(Reasonable):同理
-
並行代碼(Parallel Code):由於不需要共享內存,所以可以並行處理純函數
柯里化(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));
通過以上的柯里化函數,我們可以把函數式編程變得簡潔,沒有冗餘。儘管有多個參數,我們仍然可以保留數學函數的定義。
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 就是把函數像 “管道” 一樣組合起來。下面展示最簡單的組合示例。
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!"
以下是一個通用的 compose 函數:
const compose = (...fns) => (...args) => fns.reduceRight((res, fn) => [fn.call(null, ...res)], args)[0];
因爲 compose 也是純函數,同樣滿足分配律:
// 滿足分配律
compose(f, compose(g, h)) === compose(compose(f, g), h);
所以不管傳參的順序如何,它都返回相同的結果,非常強大 👍
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 風格
Pointfree 的意思是不使用所要操作的數據,只合成運算過程。下面是使用 Ramda[1] 函數庫的pipe
方法實現 Pointfree 的例子,選自阮一峯老師的《Pointfree 編程風格指南》[2]。
var str = 'Lorem ipsum dolor sit amet consectetur adipiscing elit';
上面字符串最長的單詞有多少個字符呢?先定義一些基本運算:
// 以空格分割單詞
var splitBySpace = s => s.split(' ');
// 每個單詞的長度
var getLength = w => w.length;
// 詞的數組轉換成長度的數組
var getLengthArr = arr => R.map(getLength, arr);
// 返回較大的數字
var getBiggerNumber = (a, b) => a > b ? a : b;
// 返回最大的一個數字
var findBiggestNumber = arr => R.reduce(getBiggerNumber, 0, arr);
然後把基本運算合成爲一個函數:
var getLongestWordLength = R.pipe(
splitBySpace,
getLengthArr,
findBiggestNumber
);
getLongestWordLength(str) // 11
可以看到,整個運算由三個步驟構成,每個步驟都有語義化的名稱,非常的清晰。這就是 Pointfree 風格的優勢。Ramda 提供了很多現成的方法,可以直接使用這些方法,省得自己定義一些常用函數(查看完整代碼 [3])。
// 上面代碼的另一種寫法
var getLongestWordLength = R.pipe(
R.split(' '),
R.map(R.length),
R.reduce(R.max, 0)
);
再看一個實戰的例子,拷貝自 Scott Sauyet 的文章《Favoring Curry》[4]。那篇文章能幫助你深入理解柯里化,強烈推薦閱讀。下面是一段服務器返回的 JSON 數據。
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 純函數的實現
下面的實現僅僅爲了基本演示,如果考慮實際開發,請參考 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]);
關於更多 Pointfree 純函數的實現可以參考 Pointfree Utilities[10]。
參考
-
《Professor Frisby’s Mostly Adequate Guide to Functional Programming》[11],翻譯版本爲《JS 函數式編程指南中文版》[12]
-
Pointfree Javascript[13]
-
Favoring Curry[14]
參考資料
[1]
Ramda: http://www.ruanyifeng.com/blog/2017/03/ramda.html
[2]
《Pointfree 編程風格指南》: 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 函數式編程指南中文版》: 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/
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/1IZwX6GIgl2-rDzS43ta1w