|
| 1 | +// 函数柯厘化 |
| 2 | +// 较少输入参数,相比一元函数. |
| 3 | +// 引用透明的直接结果就是元数与程序复杂性成正比 |
| 4 | +// 柯理化:表意为在函数所有参数被输入之前,函数会被一直挂起,延迟执行。直到所有参数传入. |
| 5 | +// 二元参数 |
| 6 | +function curry2(fn) { |
| 7 | + return function (firstArg) { |
| 8 | + return function (secondArg) { |
| 9 | + return fn(firstArg, secondArg); |
| 10 | + }; |
| 11 | + }; |
| 12 | +} |
| 13 | + |
| 14 | +// 柯里化是词法作用域的应用,闭包. |
| 15 | +// 使用curry2 |
| 16 | + |
| 17 | +// 元祖定义name输出类型 |
| 18 | +const StringPair = Tuple(String, String); |
| 19 | + |
| 20 | +const name = curry2(function (a, b) { |
| 21 | + return new StringPair(a, b); |
| 22 | +}); |
| 23 | +let { _1: first, _2: last } = name('Curry')('Haskell'); |
| 24 | + |
| 25 | +console.log(first, last); |
| 26 | + |
| 27 | +// Tuple 中 类型检测函数实现 checkType |
| 28 | +const checkTypeCopy = curry2(function (typeDef, actualType) { |
| 29 | + if (R.is(typeDef, actualType)) { |
| 30 | + return actualType; |
| 31 | + } else { |
| 32 | + throw new TypeError( |
| 33 | + `Type mismatch Expected [ + ${typeDef} ] but found [ ${typeof actualType} ]` |
| 34 | + ); |
| 35 | + } |
| 36 | +}); |
| 37 | + |
| 38 | +// right |
| 39 | +res = checkTypeCopy(String)('Curry'); |
| 40 | +console.log(res); |
| 41 | +// right |
| 42 | +res = checkTypeCopy(Number)(1); |
| 43 | +console.log(res); |
| 44 | +res; |
| 45 | +// right |
| 46 | +res = checkTypeCopy(Date)(new Date()); |
| 47 | +console.log(res); |
| 48 | +// wrong |
| 49 | +res = checkTypeCopy(Object)(NaN); // TypeError: Type mismatch Expected [ + function Object() { [native code] } ] but found [ number ] |
| 50 | + |
| 51 | +// 柯里化,从上面的demo来看可以理解为多元函数参数分步处理 |
| 52 | +// 多元函数 |
| 53 | +// fullname :: (String, String) -> String |
| 54 | +const fullname = (firtst, last) => { |
| 55 | + //..... |
| 56 | +}; |
| 57 | + |
| 58 | +// 基础声明参数数量人工创建嵌套作用域,闭包应用实现柯里化效果 |
| 59 | +const fullnameCopy = function (fn) { |
| 60 | + return function (first) { |
| 61 | + return function (last) { |
| 62 | + return fn(first, last); |
| 63 | + }; |
| 64 | + }; |
| 65 | +}; |
| 66 | + |
| 67 | +// 柯里化应用 |
| 68 | +// 1. 仿真函数接口 |
| 69 | +// 2. 实现可重用模块化函数模版 |
0 commit comments