Skip to content

Commit 369e51b

Browse files
author
wangshan
committed
feat: 柯里化释义
- 柯里化简化函数参数数量,注:并非舍弃参数 - 常见柯里化库Ramda.js-curry应用 - 柯里化应用-仿真函数实现-可重用模块化函数模版实现 - 柯里化-使用js内置词法作用域(闭包)实现
1 parent 009a06a commit 369e51b

File tree

2 files changed

+70
-2
lines changed

2 files changed

+70
-2
lines changed

index.html

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111
<script src="./node_modules/lodash/lodash.js"></script>
1212
<script src="./node_modules/ramda/dist/ramda.js"></script>
1313
<script src="./src/ch04/utils/util.js"></script>
14-
<script src="./src/ch02/func_ch02_1.js"></script>
15-
<script src="src/ch04/func_ch04_1.js"></script>
14+
<script src="src/ch04/func_ch04_4.js"></script>
1615
</body>
1716
</html>

src/ch04/func_ch04_4.js

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
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

Comments
 (0)