DevilKing's blog

冷灯看剑,剑上几分功名?炉香无需计苍生,纵一穿烟逝,万丈云埋,孤阳还照古陵

0%

Function Program

原文

offers a helpful twist on typical functional programming operations (like map(..), compose(..), etc)

主要是从JS的角度来说明functional programming,例如,ES6

大量的FP libraries in JS

1
2
3
4
5
6
7
8
9
10

function uppercase(v) { return v.toUpperCase(); }

var words = ["Now","Is","The","Time"];
var moreWords = ["The","Quick","Brown","Fox"];

var f = R.map( uppercase );
f( words ); // ["NOW","IS","THE","TIME"]
f( moreWords ); // ["THE","QUICK","BROWN","FOX"]

使用Ramda, R.map(..)是柯西化的

我们注意到这部分的功能是,先使用mapper的功能,也就是uppercase的分发,然后才是arrays的功能(遍历?)

因为是柯西化的,所以我们可以进行反转

1
2
3
4
5
6

var p = R.flip( R.map )( words );

p( lowercase ); // ["now","is","the","time"]
p( uppercase ); // ["NOW","IS","THE","TIME"]

这样,先进行遍历array的操作,然后才是相关功能的mapper? 这里面使用了R.flip(..)这样的功能进行参数的交换

由此引出的问题,在functional programming中,需要记住参数的顺序

1
2
3
4
5
6
7
8
9
10
11

function concatStr(s1,s2) { return s1 + s2; }

var words = ["Now","Is","The","Time"];

_.reduce( concatStr, _, words );
// NowIsTheTime

_.reduce( concatStr, "Str: ", words );
// Str: NowIsTheTime

这里面_.reduce(..)使用这样的参数顺序reducerFunction, initialValue, arr。但我们一般情况下很少填写initialValue

这样的一个解决办法就是Named Arguments。这样的一种方案不是跟python很类似?